0
0
NginxHow-ToBeginner · 3 min read

How to Use log_format Directive in Nginx for Custom Logs

Use the log_format directive in the http block of your Nginx configuration to define a custom log format by specifying a name and a format string with variables. Then, reference this format name in the access_log directive to apply it to your logs.
📐

Syntax

The log_format directive defines a custom format for access logs. It is placed inside the http block and has two parts: a name for the format and a string that specifies what data to log using variables.

  • Name: Identifier for the log format.
  • Format string: Text with variables like $remote_addr for client IP.
nginx
log_format name 'format string';
💻

Example

This example shows how to create a custom log format named main that logs client IP, time, request line, status, and user agent. Then it applies this format to the access log.

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

    access_log /var/log/nginx/access.log main;

    server {
        listen 80;
        server_name example.com;

        location / {
            root /usr/share/nginx/html;
            index index.html;
        }
    }
}
Output
Sample log line generated: 127.0.0.1 - - [27/Apr/2024:12:00:00 +0000] "GET / HTTP/1.1" 200 612 "-" "Mozilla/5.0 (compatible)"
⚠️

Common Pitfalls

Common mistakes when using log_format include:

  • Defining log_format outside the http block, which causes errors.
  • Forgetting to specify the custom format name in the access_log directive, so the default format is used instead.
  • Incorrectly quoting the format string, leading to syntax errors.
nginx
http {
    # Wrong: log_format outside http block
}

log_format main '$remote_addr - $remote_user [$time_local] "$request"';

# Correct usage:
http {
    log_format main '$remote_addr - $remote_user [$time_local] "$request"';
    access_log /var/log/nginx/access.log main;
}
📊

Quick Reference

DirectiveDescriptionExample
log_formatDefines a custom log format with a name and format stringlog_format main '$remote_addr - $request';
access_logEnables access logging and specifies log file and formataccess_log /var/log/nginx/access.log main;
VariablesPlaceholders for request data like client IP, status, user agent$remote_addr, $status, $http_user_agent

Key Takeaways

Define custom log formats inside the http block using log_format with a name and format string.
Use the custom format name in access_log to apply your log format to log files.
Always quote the format string properly to avoid syntax errors.
Place log_format directive only inside the http block, not server or location blocks.
Use Nginx variables like $remote_addr and $request to customize log details.