【node】log4js日志

官方文档

更多详细参数查看官方文档: https://log4js-node.github.io/log4js-node/

日志级别

级别 含义 适用场景
TRACE 追踪详细的运行信息 开发环境,调试代码
DEBUG 调试信息 开发环境,测试环境
INFO 状态信息或重要事件 生产环境,监控程序运行状态
WARN 警告信息,潜在问题 生产环境,提醒潜在问题
ERROR 错误信息,程序仍可运行 生产环境,记录需要关注的错误
FATAL 致命错误,程序可能无法运行 生产环境,记录致命错误
MARK 标记或特殊事件 根据需求使用

常用配置代码

@/utils/logger.js

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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import path from "node:path";
import log4js from "log4js";

log4js.configure({
appenders: {
// 标准输出流
out: { type: "stdout" },
// 日期文件输出
dateFile: {
type: "dateFile",
filename: path.resolve(import.meta.dirname, "../", "logs", "dateFile", "log-name.log"),
pattern: "yyyy-MM-dd_hh-mm-ss",
alwaysIncludePattern: true,
fileNameSep: ".",
keepFileExt: true,
encoding: "utf-8",
maxLogSize: "10M",
numBackups: 5,
mode: 0o666,
layout: {
type: "basic",
},
},
// 文件输出
file: {
type: "file",
filename: path.resolve(import.meta.dirname, "../", "logs", "file", "log-name.log"),
maxLogSize: "10M",
backups: 5,
encoding: "utf-8",
mode: 0o666,
keepFileExt: true,
layout: {
type: "basic",
},
},
// 文件输出(同步)
fileSync: {
type: "fileSync",
filename: path.resolve(import.meta.dirname, "../", "logs", "fileSync", "log-name.log"),
maxLogSize: "10M",
backups: 5,
encoding: "utf-8",
mode: 0o666,
keepFileExt: true,
layout: {
type: "basic",
},
},
},
// 日志等级 level 值,等级由低到高,假设日志等级为 info,那么小于 info 的日志不会输出
// ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < MARK < OFF
categories: {
default: { appenders: ["out"], level: "all" },
app1: { appenders: ["dateFile"], level: "all" },
app2: { appenders: ["file"], level: "all" },
app3: { appenders: ["fileSync"], level: "all" },
},
});

export const logger = log4js.getLogger("default");
export const loggerDateFile = log4js.getLogger("app1");
export const loggerFile = log4js.getLogger("app2");
export const loggerFileSync = log4js.getLogger("app3");

使用

1
2
3
4
5
6
7
8
9
import { logger } from "@/utils/logger.js";

logger.trace("trace");
logger.debug("debug");
logger.info("info");
logger.warn("warn");
logger.error("error");
logger.fatal("fatal");
logger.mark("mark");