How to configure a custom log format in nginx?

Published on Aug. 22, 2023, 12:19 p.m.

To configure a custom log format in NGINX, you can use the log_format directive in the configuration file. This directive allows you to define the format of logged messages based on the variables provided by NGINX. Here is an example configuration:

http {
    log_format mylogformat '$remote_addr - $remote_user [$time_local] '
                            '"$request" $status $body_bytes_sent '
                            '"$http_referer" "$http_user_agent"';
    access_log /var/log/nginx/access.log mylogformat;
}

In this example, we are defining a custom log format named mylogformat that includes the IP address, authenticated user (if any), timestamp, request method and URI, HTTP status code, number of bytes sent in the response body, referring URL, and user agent string. Then, we specify the access_log directive with the path to the log file and the name of the log format.

You can also use conditional statements and other directives to customize the log format based on specific criteria, such as the request HTTP method, response status code, or user agent.

I hope that helps! Let me know if you have any other questions or if there’s anything else I can help you with.

Tags: