nginx/njs

How to log to a separate log file instead of error log file?

Closed this issue · 2 comments

Hi,
I found that all njs logs are mixed with nginx error log.
Are there any ways to make them apart?

Hi @baiyuxiong,

There is no way to separate njs logs and nginx error logs as of now.

One way to separate them is to filter the error.log file as
grep '\[info\].*js' error.log
to get NJS logs.

When it comes to logging your own logs separately or per server/location, there is a trick to logging.

First you create your own SysLog server with JS, which waits for messages, and you parse them into JSON. You then evaluate this based on an ID, you discard everything else, or you log “Basic”. You can split everything with an ID (by me "ff_http_id":3) separately into files or into a DB, as you like:


public static readonly SYSLOG_TAG = 'nginx';

......

syslog = new SysLogServer();
....
syslog.setOnMessage((
            _sysLogServer,
            msg
        ) => {
            
            const parts = msg.toString().split(`${NginxService.SYSLOG_TAG}: `);

            try {
                const nginxLog = JSON.parse(parts[1]);
....

In the nginx config you log a log_format:

log_format ff_h_accesslogs_3 escape=json '{"source":"nginx","source_type":"http","logging":"access","ff_http_id":3,"time":"$time_iso8601","host":"$remote_addr","proxy_protocol_addr":"$proxy_protocol_addr","forwardedfor":"$http_x_forwarded_for","req":"$request","method":"$request_method","scheme":"$scheme","uri":"$request_uri","status":"$status","size":"$body_bytes_sent","referer":"$http_referer","ua":"$http_user_agent","reqtime":"$request_time","runtime":"$upstream_http_x_runtime","apptime":"$upstream_response_time","cache":"$upstream_http_x_cache","vhost":"$host"}';

then:

	server {
		listen 10443 ssl http2 proxy_protocol;
		access_log syslog:server=127.0.0.1:514,tag=nginx ff_h_accesslogs_3;

In njs javascript you can now put together such a JSON string and log it:

async function some(s: NginxHTTPRequest) {
        s.warn('{"source":"njs", "ff_http_id":3, ......}');

Maybe this approach will help you :)