Sending all nginx logs to journald

Posted on 2025-04-13 in Trucs et astuces

As part of my work to uniformize my server setup around systemd, I decided to make nginx log everything with journald. By default, it logs accesses and errors in log files under /var/log/nginx. I already had one log file per vhost.

To do the change, I changed my access_log and error_log directives in each vhost to:

access_log syslog:server=unix:/dev/log main;
error_log syslog:server=unix:/dev/log;

Here:

  • /dev/log is a socket you can use to send logs to journald.
  • main is my logging configuration. I can’t use the default combined because it may not log the domain for which the request was made under some conditions I didn’t bother to dig into. It would cause problems to filter logs by domain.

Note

error_log cannot have a logging configuration.

Here’s how the main logging configuration is (in /etc/nginx.conf in the main http block):

log_format  main  '$http_host - $remote_addr - $remote_user [$time_local] "$request" '
            '$status $body_bytes_sent "$http_referer" '
            '"$http_user_agent" "$http_x_forwarded_for"';

I only added $http_host at the start from the default main logging configuration suggested in the default configuration. Here’s how I filter logs by domains:

# View new entries with --follow
# Select service nginx with --unit nginx
# grep the results with --grep jujens.eu (regular expressions possible)
journalctl --follow --unit nginx --grep "jujens.eu"

Other articles regarding my switch to more systemd: