PM2集群环境使用log4js打印日志
pm2的日志性能很好,但log4js写起来更爽,用Node做开发追求的不就是敏捷开发么?
环境以及安装pm2-intercom
$ node -v
v10.16.0
$ npm ls log4js express ts-node typescript
├── express@4.17.1
├── log4js@6.1.2
├── ts-node@8.4.1
└── typescript@3.7.2
$ pm2 -v
4.1.2
$ pm2 install pm2-intercom
目录结构
src
├── app.ts
└── config
├── log4js.json
└── pm2.json
log4js.json
{
"appenders" : {
"console" : {
"type": "console"
},
"global_out" : {
"type" : "dateFile",
"filename" : "/home/node/logs/xxProject/global_out",
"layout" : {
"type" : "pattern",
"pattern": "|%d|%p|%c|%m|"
},
"alwaysIncludePattern": true,
"pattern" : "yyyy-MM-dd.log"
},
"global_error" : {
"type" : "dateFile",
"filename" : "/home/node/logs/xxProject/global_error",
"layout" : {
"type" : "pattern",
"pattern": "|%d|%p|%c|%m|"
},
"alwaysIncludePattern": true,
"pattern" : "yyyy-MM-dd.log"
},
"global_error_filter": {
"type" : "logLevelFilter",
"appender": "global_error",
"level" : "error"
},
"console_info_filter": {
"type" : "logLevelFilter",
"appender": "console",
"level" : "info"
}
},
"categories" : {
"default": {
"appenders" : [
"console_info_filter",
"global_out",
"global_error_filter"
],
"level" : "info",
"enableCallStack": true
}
},
"pm2" : true,
"pm2InstanceVar": "INSTANCE_ID"
}
app.ts片段
// pm2 install pm2-intercom
const log4js = require('log4js');
log4js.configure('./config/log4js.json');
const logger = log4js.getLogger('console');
console.log = logger.info.bind(logger);
console.info = logger.info.bind(logger);
console.error = logger.error.bind(logger);
console.debug = logger.debug.bind(logger);
console.trace = logger.trace.bind(logger);
console.warn = logger.warn.bind(logger);
pm2.json
{
"apps": [
{
"name" : "MobileFreelancer",
"instances" : 4,
"exec_mode" : "cluster",
"script" : "../node_modules/.bin/ts-node",
"args" : "-P ../tsconfig.json -r tsconfig-paths/register ./app.js",
"watch" : false,
"ignore_watch" : [
"node_modules"
],
"env" : {
"TZ" : "Asia/Shanghai",
"NODE_PATH": ".",
"NODE_ENV" : "development"
},
"env_production" : {
"TZ" : "Asia/Shanghai",
"NODE_PATH": ".",
"NODE_ENV" : "production"
},
"error_file" : "/home/node/logs/xxProject/pm2-error.log",
"out_file" : "/dev/null",
"combine_logs" : true,
"log_date_format": "YYYY-MM-DD HH:mm Z",
"instance_var" : "INSTANCE_ID"
}
]
}
启动命令 package.json -> scripts
{
"build:rm" : "rm -rf dist/ && mkdir dist/",
"build:copy": "cp -r src/config/ dist/",
"build" : "npm run build:rm && npm run build:copy && node_modules/.bin/tsc -b",
"buildOnly" : "npm run build:copy && node_modules/.bin/tsc -b",
"watch" : "npm run build:rm && npm run build:copy && node_modules/.bin/tsc-watch",
"dev" : "cd src && env TZ='Asia/Shanghai' NODE_PATH=. NODE_ENV=development ../node_modules/.bin/ts-node -P ../tsconfig.json -r tsconfig-paths/register ./app.ts",
"pm2dev" : "npm run buildOnly && cd dist/ && pm2 startOrGracefulReload config/pm2.json",
"pm2" : "cd dist/ && pm2 startOrGracefulReload config/pm2.json --env production"
}