0
0
NginxHow-ToBeginner · 4 min read

How to Configure Logging in Nginx: Syntax and Examples

To configure logging in nginx, use the access_log directive to specify the access log file and format, and the error_log directive to set the error log file and log level. These directives are placed inside the http, server, or location blocks in the nginx.conf file.
📐

Syntax

The main directives to configure logging in nginx are:

  • access_log: Defines the file path and format for access logs.
  • error_log: Defines the file path and log level for error logs.

These directives can be placed in the http, server, or location blocks to control logging scope.

nginx
access_log <path> [format [buffer=size] [gzip[=level]] [flush=time]];
error_log <path> [level];
💻

Example

This example shows how to configure both access and error logging inside the http block of nginx.conf. It sets a custom log format and specifies log files.

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

    access_log /var/log/nginx/access.log main;
    error_log /var/log/nginx/error.log warn;

    server {
        listen 80;
        server_name example.com;

        location / {
            root /usr/share/nginx/html;
            index index.html;
        }
    }
}
⚠️

Common Pitfalls

Common mistakes when configuring logging in nginx include:

  • Using incorrect file paths that the nginx user cannot write to, causing logging to fail silently.
  • Not specifying a log format, which defaults to the combined format but may not suit your needs.
  • Placing logging directives in the wrong block, leading to unexpected logging behavior.
  • Setting an invalid log level in error_log, which causes errors on reload.
nginx
## Wrong: Using a non-writable path
access_log /root/access.log;

## Right: Use a writable path
access_log /var/log/nginx/access.log;
📊

Quick Reference

DirectivePurposeExample
access_logSets access log file and formataccess_log /var/log/nginx/access.log main;
error_logSets error log file and log levelerror_log /var/log/nginx/error.log error;
log_formatDefines custom log formatlog_format main '$remote_addr - $remote_user [$time_local] "$request"';
log_levelControls error log verbosityerror_log /var/log/nginx/error.log warn;

Key Takeaways

Use access_log and error_log directives inside http, server, or location blocks to configure logging.
Always ensure log file paths are writable by the nginx user to avoid silent failures.
Define a custom log_format for clearer and more useful access logs.
Set appropriate error log levels like error, warn, or info to control log verbosity.
Place logging directives carefully to control the scope of logging as needed.