Skip to content

Commit

Permalink
feat: add log files configuration in winston
Browse files Browse the repository at this point in the history
  • Loading branch information
wajeshubham committed Aug 27, 2024
1 parent cdbc1e1 commit ac5321b
Show file tree
Hide file tree
Showing 8 changed files with 29 additions and 19 deletions.
5 changes: 3 additions & 2 deletions src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@ import responseinspectionRouter from "./routes/kitchen-sink/responseinspection.r
import statuscodeRouter from "./routes/kitchen-sink/statuscode.routes.js";

// * Seeding handlers
import logger from "./logger/winston.logger.js";
import { avoidInProduction } from "./middlewares/auth.middlewares.js";
import { seedChatApp } from "./seeds/chat-app.seeds.js";
import { seedEcommerce } from "./seeds/ecommerce.seeds.js";
Expand Down Expand Up @@ -232,7 +233,7 @@ app.delete("/api/v1/reset-db", avoidInProduction, async (req, res) => {
fs.readdir(directory, (err, files) => {
if (err) {
// fail silently
console.log("Error while removing the images: ", err);
logger.error("Error while removing the images: ", err);
} else {
for (const file of files) {
if (file === ".gitkeep") continue;
Expand All @@ -245,7 +246,7 @@ app.delete("/api/v1/reset-db", avoidInProduction, async (req, res) => {
// remove the seeded users if exist
fs.unlink("./public/temp/seed-credentials.json", (err) => {
// fail silently
if (err) console.log("Seed credentials are missing.");
if (err) logger.error("Seed credentials are missing.");
});
return res
.status(200)
Expand Down
5 changes: 3 additions & 2 deletions src/db/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import mongoose from "mongoose";
import { DB_NAME } from "../constants.js";
import logger from "../logger/winston.logger.js";

/** @type {typeof mongoose | undefined} */
export let dbInstance = undefined;
Expand All @@ -10,11 +11,11 @@ const connectDB = async () => {
`${process.env.MONGODB_URI}/${DB_NAME}`
);
dbInstance = connectionInstance;
console.log(
logger.info(
`\n☘️ MongoDB Connected! Db host: ${connectionInstance.connection.host}\n`
);
} catch (error) {
console.log("MongoDB connection error: ", error);
logger.error("MongoDB connection error: ", error);
process.exit(1);
}
};
Expand Down
9 changes: 5 additions & 4 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import dotenv from "dotenv";
import { httpServer } from "./app.js";
import connectDB from "./db/index.js";
import logger from "./logger/winston.logger.js";

dotenv.config({
path: "./.env",
Expand All @@ -14,12 +15,12 @@ const majorNodeVersion = +process.env.NODE_VERSION?.split(".")[0] || 0;

const startServer = () => {
httpServer.listen(process.env.PORT || 8080, () => {
console.info(
logger.info(
`📑 Visit the documentation at: http://localhost:${
process.env.PORT || 8080
}`
);
console.log("⚙️ Server is running on port: " + process.env.PORT);
logger.info("⚙️ Server is running on port: " + process.env.PORT);
});
};

Expand All @@ -28,14 +29,14 @@ if (majorNodeVersion >= 14) {
await connectDB();
startServer();
} catch (err) {
console.log("Mongo db connect error: ", err);
logger.error("Mongo db connect error: ", err);
}
} else {
connectDB()
.then(() => {
startServer();
})
.catch((err) => {
console.log("Mongo db connect error: ", err);
logger.error("Mongo db connect error: ", err);
});
}
3 changes: 3 additions & 0 deletions src/logger/winston.logger.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ const format = winston.format.combine(
const transports = [
// Allow the use the console to print the messages
new winston.transports.Console(),
new winston.transports.File({ filename: "logs/error.log", level: "error" }),
new winston.transports.File({ filename: "logs/info.log", level: "info" }),
new winston.transports.File({ filename: "logs/http.log", level: "http" }),
];

// Create the logger instance that has to be exported
Expand Down
3 changes: 2 additions & 1 deletion src/seeds/user.seeds.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { faker } from "@faker-js/faker";
import fs from "fs";
import { AvailableUserRoles } from "../constants.js";
import logger from "../logger/winston.logger.js";
import { User } from "../models/apps/auth/user.models.js";
import { Cart } from "../models/apps/ecommerce/cart.models.js";
import { EcomProfile } from "../models/apps/ecommerce/profile.models.js";
Expand Down Expand Up @@ -64,7 +65,7 @@ const seedUsers = asyncHandler(async (req, res, next) => {
json,
"utf8",
(err) => {
console.log("Error while writing the credentials", err);
logger.error("Error while writing the credentials", err);
}
);

Expand Down
7 changes: 4 additions & 3 deletions src/utils/helpers.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import fs from "fs";
import mongoose from "mongoose";
import logger from "../logger/winston.logger.js";

/**
*
Expand Down Expand Up @@ -113,9 +114,9 @@ export const getLocalPath = (fileName) => {
*/
export const removeLocalFile = (localPath) => {
fs.unlink(localPath, (err) => {
if (err) console.log("Error while removing local files: ", err);
if (err) logger.error("Error while removing local files: ", err);
else {
console.log("Removed local: ", localPath);
logger.info("Removed local: ", localPath);
}
});
};
Expand Down Expand Up @@ -154,7 +155,7 @@ export const removeUnusedMulterImageFilesOnError = (req) => {
}
} catch (error) {
// fail silently
console.log("Error while removing image files: ", error);
logger.error("Error while removing image files: ", error);
}
};

Expand Down
5 changes: 3 additions & 2 deletions src/utils/mail.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import Mailgen from "mailgen";
import nodemailer from "nodemailer";
import { Product } from "../models/apps/ecommerce/product.models.js";
import logger from "../logger/winston.logger.js";

/**
*
Expand Down Expand Up @@ -46,10 +47,10 @@ const sendEmail = async (options) => {
} catch (error) {
// As sending email is not strongly coupled to the business logic it is not worth to raise an error when email sending fails
// So it's better to fail silently rather than breaking the app
console.log(
logger.error(
"Email service failed silently. Make sure you have provided your MAILTRAP credentials in the .env file"
);
console.log("Error: ", error);
logger.error("Error: ", error);
}
};

Expand Down
11 changes: 6 additions & 5 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2726,7 +2726,7 @@ [email protected]:
resolved "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz"
integrity sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==

ejs@^3.1.10, ejs@^3.1.6:
ejs@^3.1.6:
version "3.1.10"
resolved "https://registry.npmjs.org/ejs/-/ejs-3.1.10.tgz#69ab8358b14e896f80cc39e62087b88500c3ac3b"
integrity sha512-UeJmFfOrAQS8OJWPZ4qtgHyWExa088/MtK5UEyoJGFH67cDEXkZSviOiKRCZ4Xij0zxI3JECgYs3oKx+AizQBA==
Expand Down Expand Up @@ -3106,14 +3106,15 @@ form-data@~2.3.2:
combined-stream "^1.0.6"
mime-types "^2.1.12"

formidable@^2.1.2, formidable@^3.5.1:
version "3.5.1"
resolved "https://registry.npmjs.org/formidable/-/formidable-3.5.1.tgz#9360a23a656f261207868b1484624c4c8d06ee1a"
integrity sha512-WJWKelbRHN41m5dumb0/k8TeAx7Id/y3a+Z7QfhxP/htI9Js5zYaEDtG8uMgG0vM0lOlqnmjE99/kfpOYi/0Og==
formidable@^2.1.2:
version "2.1.2"
resolved "https://registry.yarnpkg.com/formidable/-/formidable-2.1.2.tgz#fa973a2bec150e4ce7cac15589d7a25fc30ebd89"
integrity sha512-CM3GuJ57US06mlpQ47YcunuUZ9jpm8Vx+P2CGt2j7HpgkKZO/DJYQ0Bobim8G6PFQmK5lOqOOdUXboU+h73A4g==
dependencies:
dezalgo "^1.0.4"
hexoid "^1.0.0"
once "^1.4.0"
qs "^6.11.0"

[email protected]:
version "0.2.0"
Expand Down

0 comments on commit ac5321b

Please sign in to comment.