Files
chuanqi-qycq-web/module/server/log4js.js
艾贤凌 6d4a72161f inint
2026-03-16 12:05:55 +08:00

89 lines
2.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import log4js from 'log4js'
// ── 日志目录相对于进程工作目录PM2 启动时建议设置 cwd 为 module/server ──
const LOG_DIR = process.env.LOG_DIR || 'logs'
const LOG_LEVEL = process.env.LOG_LEVEL || 'info'
/**
* log4js 配置:
* - console : 控制台彩色输出(开发期友好)
* - file : logs/app.log —— 所有 ≥ info 的日志,按天轮转,保留 30 天
* - error : logs/error.log —— 仅 warn/error按天轮转保留 60 天
*
* 生产环境可通过环境变量控制:
* LOG_DIR 日志目录 默认 logs
* LOG_LEVEL 日志级别 默认 info
*/
export const configure = {
appenders: {
// 控制台
console: {
type: 'console',
layout: {
type: 'pattern',
pattern: '%[[%d{hh:mm:ss}] [%p] [%c]%] %m',
},
},
// 全量文件日志(按日期轮转)
file: {
type: 'dateFile',
filename: `${LOG_DIR}/app`,
pattern: '.yyyy-MM-dd.log',
alwaysIncludePattern: true,
layout: {
type: 'pattern',
pattern: '[%d{yyyy-MM-dd hh:mm:ss}] [%p] [%c] %m',
},
numBackups: 30, // 保留最近 30 天
compress: true, // 压缩旧日志
keepFileExt: false,
},
// 错误日志(仅 WARN / ERROR
errorFile: {
type: 'dateFile',
filename: `${LOG_DIR}/error`,
pattern: '.yyyy-MM-dd.log',
alwaysIncludePattern: true,
layout: {
type: 'pattern',
pattern: '[%d{yyyy-MM-dd hh:mm:ss}] [%p] [%c] %m',
},
numBackups: 60, // 保留 60 天
compress: true,
},
// 过滤器:只让 WARN 及以上进入 errorFile
errorFilter: {
type: 'logLevelFilter',
appender: 'errorFile',
level: 'warn',
},
},
categories: {
// 开发模式:只输出到控制台
default: {
appenders: process.env.NODE_ENV === 'production'
? ['console', 'file', 'errorFilter']
: ['console'],
level: LOG_LEVEL,
},
// MySQL 日志独立分类(可在需要时调整级别)
mysql: {
appenders: process.env.NODE_ENV === 'production'
? ['file', 'errorFilter']
: ['console'],
level: 'warn', // MySQL 日志默认只记录 warn 及以上
},
},
}
log4js.configure(configure)
export const manager = log4js
export const mysql = log4js.getLogger('mysql')
export const koa = log4js.getLogger('koa')