如何在pm2 cluster模式下,使用winston-daily-rotate-file

问题:

最近用nodejs+express写了一个WebServer类应用。其中使用pm2 cluster模式进行进程管理,nodejs代码中,使用winston-daily-rotate-file进行log记录。其中winston-daily-rotate-file配置如下:

如何在pm2 cluster模式下,使用winston-daily-rotate-file_第1张图片

所以问题来了,发现其中maxFiles设置不起作用,winston-daily-rotate-file并没有删除多余的日志文件


原因:

查看了一下winston-daily-rotate-file的源代码,发现新版的winston-daily-rotate-file使用file-stream-rotator进行文件rotation的管理,其中file-stream-rotator把所产生的的文件信息放入和文件同目录下的.audit.json中:


其中内容类似如下:

如何在pm2 cluster模式下,使用winston-daily-rotate-file_第2张图片

因为pm2的cluster模式会根据cpu的核数,启动多个进程,但是winston-daily-rotate-file的配置,导致多个进程共享一个同一个目录(也就是./logs),这会导致.audit.json相互覆盖,从而丢失了一些日志文件的记录信息,因此file-stream-rotator无法对他们进行管理。


解决方案:

1,每个进程应该有自己的log文件夹,这样不会产生.audit.json覆盖的问题

2,要考虑重启的问题,所以每个文件夹的名称要相对稳定,每次重启时,新的进程还是可以找到已经创建的.audit.json文件,使得file-stream-rotator可以读取这些已经创建的日志的文件信息,并对他们进行管理,所以winston-daily-rotate-file的配置如下:

如何在pm2 cluster模式下,使用winston-daily-rotate-file_第3张图片

你可能感兴趣的:(Nodejs)