Nginx – Pass host from nginx to rsyslog

debiannginxrsyslogsyslog

I have a cluster of nginx web servers and a separate syslog server running rsyslog. The nginx vhost looks like this:

access_log      syslog:server=10.0.0.51,facility=local1,severity=info combined;
error_log       syslog:server=10.0.0.51,facility=local2 debug;

And the custom rsyslog config like this:

$template access_log,"/var/syslog/%HOSTNAME%/%PROGRAMNAME%/access.log"
$template error_log,"/var/syslog/%HOSTNAME%/%PROGRAMNAME%/error.log"
local1.*        -?access_log
local2.*        -?error_log

It works great but I would like to create separate log files on rsyslog for the different vhosts, so, e.g.,

/var/syslog/my-hostname/nginx/example.org-access.log

/var/syslog/my-hostname/nginx/somedomain.com-access.log

And so on. How can I pass the host from nginx to rsyslog?

Best Answer

Not able to comment, but maybe this will get you started in the right direction.

Nginx allows you to set tags for each log. From the documentation for nginx syslog:

tag=string

Sets the tag of syslog messages. Default is “nginx”.

For example I have this in my config:

access_log      syslog:server=server,tag=nginx_access;

For your site configuration you can set access and error logs per virtual server:

server {
    listen 80;
    server_name foo1.local;
    location /var/www/site1;
    access_log      syslog:server=server,tag=nginx_access_site1;
}

server {
    listen 80;
    server_name foo2.local;
    location /var/www/site2;
    access_log      syslog:server=server,tag=nginx_access_site2;
}

Now you should be able to filter these messages based on the tags. From How to filter rsyslog messages by tags you can set up a configuration file:

:syslogtag, isequal, "nginx_access_site1:" /var/syslog/my-hostname/nginx/site1-access.log
& stop

:syslogtag, isequal, "nginx_access_site2:" /var/syslog/my-hostname/nginx/site2-access.log
& stop

You also need to make sure that whatever you call this config file, it needs to get loaded before your default configs (which seems to be 50-default.conf) - so for example you could name it 20-nginx.conf.

Related Topic