Friday 13 December 2019

NGINX: Specify error and access logs for specific requests

You can set the error and access logs for a specific request using error_log, access_log directives.

Example
location = /about{
    error_log /nginx_logs/my_error.log;
    access_log /nginx_logs/my_access.log;

    return 200 "Hello Welcome to NGINX";
}

nginx.conf
events {
    
}

http {
    include mime.types;

    server {
        listen 9090;

        server_name localhost;

        location = /about{
            error_log /nginx_logs/my_error.log;
            access_log /nginx_logs/my_access.log;

            return 200 "Hello Welcome to NGINX";
        }

        location = /not_found{
            return 404 "File can't be found";
        }
    }
}

Validate and reload the configutation.
$sudo nginx -t
nginx: the configuration file /usr/local/etc/nginx/nginx.conf syntax is ok
nginx: configuration file /usr/local/etc/nginx/nginx.conf test is successful
$
$sudo nginx -s reload

When you open the directory /nginx_logs, you can see two files my_error.log and my_access.log files are created.

$ls /nginx_logs/
my_access.log   my_error.log

Open the url 'http://localhost:9090/about' in browser, you can see below screen.


Open the file ‘/nginx_logs/my_access.log’ to check whether request is logged or not.

$cat /nginx_logs/my_access.log
127.0.0.1 - - [16/Oct/2019:11:25:51 +0530] "GET /about HTTP/1.1" 200 22 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36"

Note
Since we specified access and error logs of the request explicitly, these are not logged to global access logs. If you want to log the requests to global logs too, you need to set them explicitly like below.

location = /about{
    error_log /nginx_logs/my_error.log;
    error_log {ERROR_LOG_FILE_LOCATION};

    access_log /nginx_logs/my_access.log;
    access_log {GLOBAL_LOG_FILE_LOCATION};

    return 200 "Hello Welcome to NGINX";
}


Previous                                                    Next                                                    Home

No comments:

Post a Comment