安装
node -v v16.14.0 pnpm install log4js
package.json
{ "type": "module", "dependencies": { "log4js": "^6.6.1" } }
示例
import log4js from "log4js"; const logger = log4js.getLogger(); logger.level = "debug"; logger.debug("Some debug messages");
运行输出
$ node app.js [2022-08-14T17:28:38.108] [DEBUG] default - Some debug messages
自定义配置,输出到文件
// log4js.config.js export default { appenders: { output: { type: "file", filename: "logger.log", maxLogSize: "1K", // K, M, G backups: 3, compress: false, layout: { type: "pattern", pattern: "[%d{yyyy-MM-dd hh:mm:ss}] [%p] %f{1} line-%l: %m", }, }, }, categories: { default: { appenders: ["output"], level: "debug", enableCallStack: true }, }, };
// app.js import log4js from "log4js"; import log4jsConfig from "./log4js.config.js"; // 配置 log4js.configure(log4jsConfig); const logger = log4js.getLogger(); logger.debug("Some debug messages");
输出格式如下
[2022-08-14 18:14:08] [DEBUG] app.js line-18: Some debug messages