CV肉饼王

Talk is cheap. Show me the code.

0%

Morgan 和 Winston

一、Morgan

1.使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const morgan = require("morgan");
const Logger = require("../models/logger");

const stream = {
write: (message) => Logger.http(message),
};

const morganMiddleware = morgan(
":method :url :status :res[content-length] - :response-time ms",
{ stream }
);

module.exports = morganMiddleware;

// 使用中间件
app.use(morganMiddleware);

二、Winston

1.使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
const winston = require("winston");

const isDevelopment = process.env.NODE_ENV === "development";

const levels = {
error: 0,
warn: 1,
info: 2,
http: 3,
debug: 4,
};

const colors = {
error: "red",
warn: "yellow",
info: "green",
http: "magenta",
debug: "white",
};

winston.addColors(colors);

const format = isDevelopment
? winston.format.combine(
winston.format.timestamp({ format: "YYYY-MM-DD HH:mm:ss:ms" }),
winston.format.colorize({ all: true }),
winston.format.printf(
(info) => `${info.timestamp} ${info.level}: ${info.message}`
)
)
: winston.format.combine(
winston.format.timestamp({ format: "YYYY-MM-DD HH:mm:ss:ms" }),
winston.format.printf(
(info) => `${info.timestamp} ${info.level}: ${info.message}`
)
);

const transports = [new winston.transports.Console()];

const Logger = winston.createLogger({
level: "debug",
levels,
format,
transports,
});

module.exports = Logger;

参考文章:

Nodejs日志系统指南