如何在日志访问 NGINX 文件中添加控制台输出 Node.js app?

How to add console outputs Node.js app in the log access NGINX file?

我有一个使用 systemd 设置的 Node.js 应用程序。 NGINX 背后的应用 运行。
我想在日志访问 NGINX 文件中添加我的 Node.js 应用程序的控制台输出?
我该怎么做?

提前致谢。

简介:

使用JFile包,文件记录可以顺利如下:

nxFile.text+='\n'+message;

详情:

添加同时登录(终端+nginx日志)的功能,然后使用它而不是直接使用console.log

var customLog=function(message){

     console.log(message);
     logNginx(message);
}

然后,实现 logNginx ,在 customLog :

中调用
    var JFile=require('jfile'); //  "npm install jfile --save" required
    let nxFile=new JFile('/var/log/nginx/access.log'); // check path before if exist in your system . IF no , change it with the available path 
    function logNginx(message){
        nxFile.text+='\n'+message; //append new line in nginx log file
      }

不要忘记安装 JFile npm install jfile,这样可以快速完成文件处理。

您可以在您的 nginx 脚本中添加以下代码。这应该有效

env NODE_BIN=/usr/bin/node
env SCRIPT_FILE="server.js"
env LOG_FILE=/var/log/logfilename.log
env RUN_AS="root"


$RUN_AS -- $NODE_BIN $SCRIPT_FILE >> $LOG_FILE 2>&1

更简单的方法是挂钩 console.log 并照常调用 console.log

var util = require('util');
var JFile = require("jfile");
var nxFile = new JFile('/var/log/nginx/access.log');
...
process.stdout.write = (function(write) {   
    return function(text, encoding, fd) {
        write.apply(process.stdout, arguments); // write to console
        nxFile.text += util.format.apply(process.stdout, arguments) + '\n'; // write to nginx
     } 
 })(process.stdout.write);

您还可以通过将上面代码中的 stdout 更改为 strerr 来定义对 console.error 的挂钩。

P.S。我没有 nginx 来验证代码。所以代码可能包含错误:)

如果你 运行 Node 作为一个 systemd 进程,console.log 进入 stdout(我相信这是默认设置),你的目标只是查看日志(或获取它们在某个地方的磁盘上),有一种比所有这些 Node 干预和挂钩更简单的方法。

您应该已经可以访问控制台日志,而无需通过 journalctl 执行任何操作。例如,我的 systemd 单元文件(在本例中位于 /etc/systemd/system/myapp.service)看起来像这样:

[Unit]
Description=My Webapp

[Service]
WorkingDirectory=/srv/webapp-dir
ExecStart=/usr/local/bin/node server.js
Restart=always
RestartSec=5
Environment=NODE_ENV=production PORT=1984
User=myuser
Group=myuser

[Install]
WantedBy=multi-user.target

并且 运行 journalctl -u myapp 显示我的应用程序的控制台日志。

如果需要,您还可以将这些日志与一些附加参数一起发送到系统日志。为此,我还将以下内容添加到我的 [Service] 目录中:

StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=myapp

这导致我的日志进入带有 myapp 标记的系统日志,如果我想使用 rsyslog 过滤,我可以在其中将它们过滤到它们自己的日志中。