在 Express 中使用 log4js

在 Express 中使用 log4js

在 config 中导出 log 配置

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
import log4js from "log4js";

log4js.configure({
appenders: {
file: {
type: "file",
filename: "log/main.log",
maxLogSize: 200480,
backups: 10
},
console: {
type: "stdout"
}
},
categories: {
development: {
appenders: ["file", "console"],
level: "all"
},
production: {
appenders: ["file"],
level: "info"
},
default: {
appenders: ["file"],
level: "info"
}
}
});

const logger =
process.env.NODE_ENV === "development"
? log4js.getLogger("development")
: log4js.getLogger("production");

export default logger;

express 中间件导入

1
2
3
4
5
6
import log4js from "log4js";
import logger from "../config/log";

export const loggerMiddleware = app => {
app.use(log4js.connectLogger(logger));
};

log4js 作为普通模块使用

1
2
import logger from "./server/config/log";
logger.info("24234234234");