How to output variable in nginx log for debugging

I am testing nginx and want to output variables to the log files. How can I do that and which log file will it go (access or error).


Solution 1:

You can send nginx variable values via headers. Handy for development.

add_header X-uri "$uri";

and you'll see in your browser's response headers:

X-uri:/index.php

I sometimes do this during local development.

It's also handy for telling you if a subsection is getting executed or not. Just sprinkle it inside your clauses to see if they're getting used.

location ~* ^.+.(jpg|jpeg|gif|css|png|js|ico|html|xml|txt)$ {
    add_header X-debug-message "A static file was served" always;
    ...
}

location ~ \.php$ {
    add_header X-debug-message "A php file was used" always;
    ...
}

So visiting a url like http://www.example.com/index.php will trigger the latter header while visiting http://www.example.com/img/my-ducky.png will trigger the former header.

Solution 2:

You can return a simple string as HTTP response:

location /
{
    return 200 $document_root;
}

Note that you have to visit a page ending with .html if you do not want to change the page's headers.

Solution 3:

You can set a custom access log format using the log_format directive which logs the variables you're interested in.

Solution 4:

Another option is to include the echo module when you build nginx, or install OpenResty which is nginx bundled with a bunch of extensions (like echo.)

Then you can simply sprinkle your configuration with statements like:

echo "args: $args"