Archive for May 12, 2016

How to Log Variables in Nginx

What is Nginx?

Nginx, (pronounced ‘enginex’), is a flexible HTTP server that can be configured for reverse proxy, mail proxy, & a generic TCP/UDP proxy server. It was created by Igor Syseov, a Russian software engineer. As of April 2016, according to Netcraft, it served or proxied about a fourth of the web’s biggest sites.

Although Nginx is popular, it is tricky to get from the setup stage to a complete stage. I frequently use Nginx, and I would describe it as flexible yet finicky.

Logging as a Problem-Solving Tool

Setting up any kind of of infrastructure is blackbox development process, which, in my opinion, requires a guess-and-check problem-solving approach. Logs are one of the principal sources of information in the check process, and are essential when refining Nginx.

Error.log and Access.log

This post focuses on access.log

1. error.log

Default location: /var/log/nginx/error.log
  • Can only be configured by severity level.
  • The severity levels are: warn, error, crit, and alert.
  • The most sensitive level is warn and alert is the least sensitive level.

2. access.log

Default location: /var/log/nginx/acess.log
  • Writes information about client requests as they are processed by the server.
  • The default setting for this log is ‘combined’ format.

Setting Variables for access.log

You can log any set of Nginx variables.

Common Variables [listed alphabetically]:
  • $host
  • $http_HOST
  • $http_referrer
  • $server_name
  • $remote_addr
  • $request
  • $upstream
  • $scheme
  • $time_local

Set the Log Format in nginx.conf

Syntax:

log_format <name of format> '"variable1" "variable2" variable3"' 

Example:

log_format debug '"[$time_local]" "$host" 
"$http_HOST"  "$server_name"  "$request" 
"$remote_addr" "$upstream_addr:"';

Set Configurations at the Server Level in sites-enabled directory

Syntax:

access_log </path/to/access.log> <name of format>

Example in Server Block:

 server {
  access_log /var/log/nginx/access.log debug;
 }

Happy logging!

Run the command below to see your access.log in real time:

tail -f /var/log/nginx/access.log

 

Resources: