Skip to content

Commit 33fcf89

Browse files
committed
feat:logger midware for http requests
1 parent 6a58466 commit 33fcf89

File tree

4 files changed

+32
-4
lines changed

4 files changed

+32
-4
lines changed

middlewares/logger.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
const logger = (req, res, next) => {
2+
const colorMethods = {
3+
GET: "green",
4+
POST: "yellow",
5+
PUT: "blue",
6+
DELETE: "red",
7+
};
8+
const color = colorMethods[req.method] || "white";
9+
10+
console.log(
11+
`${req.method} ${req.protocol}://${req.get("host")}${req.originalUrl}`[
12+
color
13+
]
14+
);
15+
next();
16+
};
17+
18+
module.exports = logger;

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
"author": "",
1313
"license": "ISC",
1414
"dependencies": {
15+
"colors": "^1.4.0",
1516
"dotenv": "^16.4.5",
1617
"express": "^4.19.2"
1718
},

pnpm-lock.yaml

Lines changed: 8 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

server.js

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
const express = require("express");
22
const path = require("path");
33
require("dotenv").config();
4-
4+
const logger = require("./middlewares/logger");
55
const app = express();
66
const PORT = process.env.PORT || 3000;
77

@@ -11,10 +11,11 @@ app.enable("trust proxy");
1111
// Middleware
1212
app.use(express.static(path.join(__dirname, "public")));
1313
app.use(express.json());
14+
app.use(logger);
1415

15-
app.get('/', (req, res) => {
16-
// res.status(200).sendFile(path.join(__dirname, "public", "index.html"));
17-
res.status(200).send("Hello World");
16+
app.get("/", logger, async (req, res) => {
17+
// res.status(200).sendFile(path.join(__dirname, "public", "index.html"));
18+
res.status(200).send("Hello World");
1819
});
1920

2021
app.listen(PORT, () =>

0 commit comments

Comments
 (0)