Learn Nginx Β· 12/13

Logging, Monitoring, and Troubleshooting

9 min read

Logging, Monitoring, and Troubleshooting with Nginx πŸ•΅οΈβ€β™‚οΈ

Welcome back to our Nginx journey! So you've got your server running, dishing out web pages like a pro. But what happens when things go wrong? Or when you get curious about who's visiting your site and what they're up to? That's where logging, monitoring, and troubleshooting come in. Think of it as installing a security camera and a friendly janitor for your Nginx server. Let's dive in!


🚦 Tracking Traffic: Understanding and Customizing Access Logs

The Problem: Imagine you've thrown a massive party (your website), and you have no idea how many people showed up, what they enjoyed the most, or if someone tried to sneak into a locked room. Without a guest list or some way to track activity, you're flying blind. In the digital world, this is where access logs come to the rescue.

The Solution: access_log

Nginx's access log is a record of every single request made to your server. It's like a bouncer at a club meticulously noting down everyone who comes in, where they go, and when they leave. This is incredibly useful for understanding your traffic, identifying popular content, and spotting unusual activity.

By default, Nginx logs every request in a file, but the real power lies in customizing what information gets logged. This is done with the log_format directive.

Defining Your Log Format

Let's start by defining a custom log format. It's like telling your bouncer exactly what information to write down for each guest.

nginx
http {
  # ... other http block configurations ...

  log_format custom_format '$remote_addr - $remote_user [$time_local] "$request" '
                         '$status $body_bytes_sent "$http_referer" '
                         '"$http_user_agent"';

  # ...
}

Let's break down what these variables mean:

  • $remote_addr: The IP address of the person visiting your site.
  • $remote_user: The user's name if they are logged in (often empty).
  • [$time_local]: The date and time of the request.
  • "$request": The actual request line, like "GET /about-us.html HTTP/1.1".
  • $status: The status code of the response (e.g., 200 for success, 404 for not found).
  • $body_bytes_sent: The size of the response sent to the client in bytes.
  • "$http_referer": The URL of the page that linked the user to your site.
  • "$http_user_agent": Information about the user's web browser and operating system.

A Fun Fact: The $http_user_agent can sometimes be quite funny. Some web crawlers have very creative user agent strings to identify themselves!

Applying Your Custom Log Format

Once you've defined your cool new format, you need to tell Nginx where to put the logs and to use that format. You do this with the access_log directive inside a server block.

nginx
server {
  # ... other server block configurations ...

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

  # ...
}

Now, your access logs located at /var/log/nginx/access.log will be written in the custom_format.

Industry Practice: Many companies add more fields to their log format, like $request_time (how long the server took to process the request) and $upstream_response_time (how long a backend service took to respond). This is super helpful for performance tuning.


🧐 Diagnosing Problems: Decoding Error Logs and Debugging Issues

The Problem: Your website suddenly shows a "502 Bad Gateway" error. A user complains a page isn't loading. What do you do? Rummaging through all your configuration files hoping to spot a typo is like looking for a needle in a haystack.

The Solution: error_log

Nginx's error log is your best friend when things go wrong. It's where Nginx writes down any problems it encounters, from minor hiccups to critical failures. Understanding how to read this log is a fundamental skill for any web administrator.

The error_log directive tells Nginx where to store these error messages and how detailed they should be.

nginx
# This can be in the main, http, server, or location context
error_log /var/log/nginx/error.log warn;

In this example, Nginx will write errors to /var/log/nginx/error.log and will only log messages of warn severity or higher.

Log Severity Levels

Nginx has several severity levels for error logs. Think of them as a scale of how much Nginx is freaking out, from a calm "hmmm, that's odd" to a screaming "THE SERVER IS ON FIRE!". Here are the most common ones, from most to least severe:

  • emerg: An emergency situation where the system is unusable.
  • alert: A serious issue that requires immediate action.
  • crit: A critical problem has occurred.
  • error: An error has occurred.
  • warn: A warning that something isn't quite right.
  • notice: A normal but significant event.
  • info: An informational message.
  • debug: Detailed debugging information.

Industry Practice: For a production server, you'll typically set the log level to warn or error. Setting it to debug can generate a massive amount of log data and slow down your server, so only use it when you're actively troubleshooting a specific problem.

A Common Error Example

Let's say you see this in your error log:

apache
2026/02/25 12:19:00 [crit] 12345#0: *1 connect() to 127.0.0.1:9000 failed (111: Connection refused) while connecting to upstream

Breaking it down:

  • 2026/02/25 12:19:00: The timestamp of the error.
  • [crit]: The severity level is critical.
  • 12345#0: The process ID and thread ID of the Nginx worker.
  • *1: The connection ID.
  • connect() to 127.0.0.1:9000 failed (111: Connection refused): This is the important part! Nginx tried to connect to a backend service at 127.0.0.1 on port 9000 (likely a PHP-FPM or similar application server), but the connection was refused. This usually means the backend service isn't running or is configured on a different port.
  • while connecting to upstream: This tells you the error happened when Nginx was trying to pass the request to another server.

See? Not so scary when you break it down!


πŸ“Š Real-time Insights: Monitoring Metrics with stub_status

The Problem: Sometimes you need a quick snapshot of your server's health. How many people are on the site right now? Is the server struggling to keep up with requests? While logs are great for historical data, they aren't ideal for a real-time pulse check.

The Solution: ngx_http_stub_status_module

The stub_status module provides a simple, real-time status page with some basic but very useful metrics about your Nginx server.

Getting Started: First, you need to make sure your Nginx installation was compiled with this module. Most standard installations include it. You can check by running nginx -V.

To enable it, you need to add a new location block to one of your server configurations:

nginx
server {
  # ... your other server configurations ...

  location /nginx_status {
    stub_status;
    allow 127.0.0.1; # Only allow access from the server itself
    deny all;       # Deny access from everyone else
  }
}

Important Security Note: The status page gives away some information about your server, so you should always restrict access to it. In the example above, we're only allowing connections from 127.0.0.1 (the server itself). You could also password-protect this location.

After adding this and reloading Nginx, you can view the status page by running curl http://127.0.0.1/nginx_status from your server. You'll see something like this:

apache
Active connections: 2
server accepts handled requests
 16 16 30
Reading: 0 Writing: 1 Waiting: 1

Here's what this means:

  • Active connections: The current number of active client connections.
  • The next line shows three numbers:
    • accepts: The total number of accepted client connections.
    • handled: The total number of handled connections.
    • requests: The total number of client requests.
  • Reading: The number of connections where Nginx is currently reading the request header.
  • Writing: The number of connections where Nginx is writing the response back to the client.
  • Waiting: The number of idle client connections waiting for a request.

This gives you a quick and easy way to see how busy your server is at any given moment.


πŸ”„ Maintenance: Implementing Log Rotation Best Practices

The Problem: Your website is a huge success! πŸŽ‰ But with all that traffic, your log files are growing... and growing... and growing. Before you know it, they've filled up your entire hard drive, and your server grinds to a halt. This is a very real and common problem!

The Solution: Log Rotation

Log rotation is the process of automatically archiving old log files and creating new ones. This keeps them at a manageable size and prevents them from consuming all your disk space.

While Nginx doesn't have a built-in log rotation feature, the standard way to handle this on Linux systems is with a utility called logrotate.

Setting up logrotate for Nginx

logrotate is usually installed by default on most Linux distributions. You can configure it by creating a new configuration file in the /etc/logrotate.d/ directory. Let's create one for Nginx:

File: /etc/logrotate.d/nginx

bash
/var/log/nginx/*.log {
  daily
  missingok
  rotate 14
  compress
  delaycompress
  notifempty
  create 0640 www-data adm
  sharedscripts
  postrotate
    if [ -f /var/run/nginx.pid ]; then
      kill -USR1 `cat /var/run/nginx.pid`
    fi
  endscript
}

Let's dissect this configuration:

  • /var/log/nginx/*.log: This tells logrotate to apply these rules to all files ending in .log inside the /var/log/nginx/ directory.
  • daily: Rotate the logs once a day.
  • missingok: Don't throw an error if a log file is missing.
  • rotate 14: Keep the last 14 rotated log files. Older ones will be deleted.
  • compress: Compress the rotated log files (usually with gzip).
  • delaycompress: Don't compress the most recent rotated log file. This gives you a chance to look at it before it gets archived.
  • notifempty: Don't rotate the log file if it's empty.
  • create 0640 www-data adm: Create a new, empty log file with the specified permissions and ownership after rotating the old one.
  • sharedscripts: Run the postrotate script once for all matching log files, not for each one individually.
  • postrotate / endscript: This block contains a script that is run after the log file is rotated. The command kill -USR1 $(cat /var/run/nginx.pid) tells the main Nginx process to reopen its log files. This is crucial so that Nginx starts writing to the new, empty log file instead of the old, rotated one.

With this in place, your server will now be a responsible citizen of your file system, cleaning up after itself and keeping things tidy. 🧹


πŸ“š Extra Reading & References

Challenge

Challenge

Configure an Nginx http block to implement robust logging and real-time monitoring based on the following requirements:

  1. Define a custom log format named detailed_metrics. This format must capture the following, in this specific order:

    • Client's real IP address
    • Local time of the request
    • The full original request line (e.g., "GET / HTTP/1.1")
    • The HTTP status code sent to the client
    • The size of the response body in bytes
    • The referrer URL
    • The client's user agent string
    • The full time taken to process the request, in seconds with millisecond resolution
    • The time spent receiving a response from the upstream server, in seconds with millisecond resolution
  2. Within the server block, configure the primary access log to be written to /var/log/nginx/main_access.log using your new detailed_metrics format.

  3. Set the server's error log to /var/log/nginx/main_error.log and ensure it only captures messages of warn severity or higher.

  4. Create a specific location block to expose real-time server statistics at the /nginx_status URI.

  5. Inside the /nginx_status location block, enable the status module.

  6. For security, restrict access to the /nginx_status endpoint, allowing requests only from localhost (127.0.0.1) and denying all other IP addresses.

Expected result

Your solution should be a complete and valid Nginx http block containing a server block.

  • A log_format directive named detailed_metrics must be defined at the http level. It must include the variables $remote_addr, $time_local, $request, $status, $body_bytes_sent, $http_referer, $http_user_agent, $request_time, and $upstream_response_time in that sequence.
  • The server block must contain an access_log directive pointing to /var/log/nginx/main_access.log and specifying the detailed_metrics format.
  • The server block must also contain an error_log directive pointing to /var/log/nginx/main_error.log with the warn level.
  • A location /nginx_status block must exist inside the server block.
  • This location block must contain the stub_status directive.
  • It must also contain the allow 127.0.0.1; and deny all; directives to correctly restrict access.
nginx

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.