pm2与log4js的结合使用
如需转载请标明出处:http://blog.csdn.net/itas109
QQ技术交流群:129518033
相关问题:
1.nodejs集群模式使用log4js
2.pm2 cluster log4js不打印日志
3.pm2 cluster log4js日志写文件丢数据
环境说明:
pm2版本:4.2.1
log4js版本:5.1.0
1.pm2简介
PM2是守护程序进程管理器,它将帮助您管理和保持应用程序在线。
官网:https://pm2.keymetrics.io
可通过NPM或Yarn安装的PM2:
$ npm install pm2 -g
# or
$ yarn global add pm2
pm2常用命令
# Fork mode
pm2 start app.js --name my-api # Name process
# Cluster mode
pm2 start app.js -i 0 # Will start maximum processes with LB depending on available CPUs
pm2 start app.js -i max # Same as above, but deprecated.
pm2 scale app +3 # Scales `app` up by 3 workers
pm2 scale app 2 # Scales `app` up or down to 2 workers total
# Listing
pm2 list # Display all processes status
pm2 jlist # Print process list in raw JSON
pm2 prettylist # Print process list in beautified JSON
pm2 describe 0 # Display all informations about a specific process
pm2 monit # Monitor all processes
# Logs
pm2 logs [--raw] # Display all processes logs in streaming
pm2 flush # Empty all log files
pm2 reloadLogs # Reload all logs
# Actions
pm2 stop all # Stop all processes
pm2 restart all # Restart all processes
pm2 reload all # Will 0s downtime reload (for NETWORKED apps)
pm2 stop 0 # Stop specific process id
pm2 restart 0 # Restart specific process id
pm2 delete 0 # Will remove process from pm2 list
pm2 delete all # Will remove all processes from pm2 list
# Misc
pm2 reset <process> # Reset meta data (restarted time...)
pm2 updatePM2 # Update in memory pm2
pm2 ping # Ensure pm2 daemon has been launched
pm2 sendSignal SIGUSR2 my-app # Send system signal to script
pm2 start app.js --no-daemon
pm2 start app.js --no-vizion
pm2 start app.js --no-autorestart
2.测试代码
主要包括console.log和log4js各函数的输出
// index.js
'use strict';
const pid = process.pid;//nodejs进程号
var log4js = require('log4js');
const express = require('express')
const app = express()
const logger = log4js.getLogger();
log4js.configure({
// 方式1
// pm2: true,
// pm2InstanceVar: 'INSTANCE_ID',
// 方式2
// disableClustering: true,
appenders: {
out: { type: 'console', layout:{type:'pattern',pattern:'%[[%d] [%p]%] - %m'} },
allLog: { type: 'dateFile', filename: './logs/app.log', layout:{type:'pattern',pattern:'[%d] [%p] - %m'} }
},
categories: {
default: { appenders: ['out', 'allLog'], level: 'debug'},
}
});
var count = 0;
function log(){
console.log("hello : %d", count++);
logger.debug("hello : %d", count++);
logger.info("hello : %d", count++);
logger.warn("hello : %d", count++);
logger.error("hello : %d", count++);
logger.fatal("***** pid : %d", pid);
}
setInterval(function () {
log();
}, 10000);
app.get('/', (req, res) => {
let info = '+++++ pid : '+ pid;
console.log(info);
logger.info(info);
res.status(200).send(info);
})
app.listen(3000, () => console.log('Example app listening on port 3000!'));
3.pm2单机与日志测试
启动app
$ pm2 start index.js --name logTest
通过pm2 moni
t和pm2 logs
测试:
console.log
正常输出控制台logjs
模块正常输出控制台和写入log文件
PM2 | App [logTest:0] starting in -fork mode-
PM2 | App [logTest:0] online
0|logTest | Example app listening on port 3000!
0|logTest | hello : 0
0|logTest | [2020-02-07T15:28:58.481] [DEBUG] - hello : 1
0|logTest | [2020-02-07T15:28:58.486] [INFO] - hello : 2
0|logTest | [2020-02-07T15:28:58.487] [WARN] - hello : 3
0|logTest | [2020-02-07T15:28:58.487] [ERROR] - hello : 4
0|logTest | [2020-02-07T15:28:58.488] [FATAL] - ***** pid : 9672
0|logTest | hello : 5
0|logTest | [2020-02-07T15:29:08.479] [DEBUG] - hello : 6
0|logTest | [2020-02-07T15:29:08.480] [INFO] - hello : 7
0|logTest | [2020-02-07T15:29:08.481] [WARN] - hello : 8
0|logTest | [2020-02-07T15:29:08.482] [ERROR] - hello : 9
0|logTest | [2020-02-07T15:29:08.482] [FATAL] - ***** pid : 9672
4.pm2集群与日志测试
启动集群
$ pm2 start index.js --name logTest -i 2
通过pm2 moni
t和pm2 logs
测试:
console.log
正常输出控制台logjs
模块均无法正常输出控制台和写入log文件
PM2 | App [logTest:0] starting in -cluster mode-
PM2 | App [logTest:0] online
PM2 | App [logTest:1] starting in -cluster mode-
PM2 | App [logTest:1] online
0|logTest | Example app listening on port 3000!
1|logTest | Example app listening on port 3000!
0|logTest | hello : 0
1|logTest | hello : 0
0|logTest | hello : 5
1|logTest | hello : 5
5.pm2集群模式下使用log4js
经过测试,在Cluster集群模式下log4js无效。
查看log4js的API文档,log4js.configure(https://log4js-node.github.io/log4js-node/api.html)说明如下:
levels
appenders
categories
pm2
(boolean) (可选) - 如果app使用pm2,设置为true,否则日志将不起作用(需要安装pm2-intercom作为pm2的模块: pm2 install pm2-intercom)pm2InstanceVar
(string) (可选, 默认为‘NODE_APP_INSTANCE’) - 如果app使用pm2,修改默认名为NODE_APP_INSTANCEdisableClustering
(boolean) (可选) - 设置为true,可能会解决pm2的日志问题。每个工作者线程会独立打印日志。但是如果将日志记录到文件,需要谨慎使用,可能会出现日志丢失问题。
set this to true if you liked the way log4js used to just ignore clustered environments, or you’re having trouble with PM2 logging. Each worker process will do its own logging. Be careful with this if you’re logging to files, weirdness can occur.
注意:不要同时使用disableClustering
和 pm2
you don’t need `disableClustering` and `pm2` in your config.
`pm2: true` turns on support for using pm2-intercom, `disableClustering: true` turns off all clustering support so it won’t use pm2-intercom.
Use one or the other, but not both.
两种解决方式:
- A.pm2参数设置
安装pm2-intercom作为pm2的模块: pm2 install pm2-intercom
,
并为log4js.configure添加参数:
pm2: true,
pm2InstanceVar: 'INSTANCE_ID'
- B. disableClustering参数设置(存在日志丢失问题)
log4js.configure添加参数:
disableClustering: true
注意:
经过测试发现,在disableClustering: true设置下,可能会出现日志写入文件(控制台正常)丢失问题。可以在~/.pm2/logs
中以pm2的日志文件作为补充。
结果(disableClustering: true方式):
PM2 | App [logTest:0] starting in -cluster mode-
PM2 | App [logTest:0] online
PM2 | App [logTest:1] starting in -cluster mode-
PM2 | App [logTest:1] online
0|logTest | Example app listening on port 3000!
1|logTest | Example app listening on port 3000!
0|logTest | hello : 0
0|logTest | [2020-02-07T15:32:13.341] [DEBUG] - hello : 1
0|logTest | [2020-02-07T15:32:13.346] [INFO] - hello : 2
0|logTest | [2020-02-07T15:32:13.347] [WARN] - hello : 3
0|logTest | [2020-02-07T15:32:13.348] [ERROR] - hello : 4
0|logTest | [2020-02-07T15:32:13.349] [FATAL] - ***** pid : 9572
1|logTest | hello : 0
1|logTest | [2020-02-07T15:32:13.519] [DEBUG] - hello : 1
1|logTest | [2020-02-07T15:32:13.523] [INFO] - hello : 2
1|logTest | [2020-02-07T15:32:13.524] [WARN] - hello : 3
1|logTest | [2020-02-07T15:32:13.524] [ERROR] - hello : 4
1|logTest | [2020-02-07T15:32:13.525] [FATAL] - ***** pid : 10336
6.其他
6.1 PM2 API
通过pm2 api启动
var pm2 = require('pm2');
pm2.connect(function(err) {
if (err) {
console.error(err);
process.exit(2);
}
pm2.start({
script : 'app.js', // Script to be run
exec_mode : 'cluster', // Allows your app to be clustered
instances : 4, // Optional: Scales your app by 4
max_memory_restart : '100M' // Optional: Restarts your app if it reaches 100Mo
}, function(err, apps) {
pm2.disconnect(); // Disconnects from PM2
if (err) throw err
});
});
6.2 pm2生态系统文件
PM2支持流程管理工作流程。通过进程文件微调每个应用程序的行为,选项,环境变量和日志文件。对于基于微服务的应用程序特别有用。支持的配置格式为Javascript,JSON和YAML。
pm2 ecosystem
这将生成一个示例ecosystem.config.js:
module.exports = {
apps : [{
name: "app",
script: "./app.js",
env: {
NODE_ENV: "development",
},
env_production: {
NODE_ENV: "production",
}
}]
}
在方便时进行编辑后,您可以通过CLI启动/重新启动/停止/删除此文件:
$ pm2 [start|restart|stop|delete] ecosystem.config.js
6.3 web管理
pm2 plus
License
License under CC BY-NC-ND 4.0: 署名-非商业使用-禁止演绎
Reference:
NULL
来源:CSDN
作者:itas109
链接:https://blog.csdn.net/itas109/article/details/104226963