How to Configure NGINX Conditional Logging

configure nginx conditional logging

NGINX is an excellent web server that is really fast, light weight and easy to configure. It also provides superb logging features making it easy to manage your web server. However, sometimes, you might not want to log all server messages, or you might want to log specific type of messages. In that case, it might be useful to know how to configure NGINX conditional logging.


How to Configure NGINX Conditional Logging

Here are the steps to configure NGINX conditional logging. We will use the ngx_http_map_module that allows you to define server variables whose values depend on other variables. We will specify a map block inside http context where we define a mapping between source and result variables.


In case of conditional logging, if the condition evaluates to 0 or empty string, the request will not be logged.


Here’s an example to exclude logging of requests with 2xx and 3xx status codes.

 map $status $condition {
  ~^[23] 0;
  default 1;
  access_log /path/to/access.log custom if=$condition;


Here’s another example that logs only debug information and ignores other information. This is useful in development phase.

 map $info $debuggable {
  default 0;
  debug 1;
  access_log /var/log/nginx/testapp_debug_access_log debug if=$debuggable;
  #logs other requests
  access_log /var/log/nginx/testapp_access.log main;


That’s it! NGINX will now log messages based on the value of your condition variables. This conditional logging applicable for both access log as well as error log.



NGINX also provides a shortcut to log different types of error messages in its error log. This method is not applicable for access log.

While specifying the location of your error log, you can use keywords like debug, info, notice, warn, error, crit, alert, or emerg to specify what error messages you need to be logged.

For example,

error_log /var/log/nginx/error_log info;


The above line will tell NGINX to log all messages of type info or more critically severe ones like crit, alert, emerg.


The following examples will log all crit messages

error_log /var/www/ crit;


Here’s an example of using 2 error logs to log different types of messages – warn and crit

server {
 listen 80;

 error_log /var/www/ warn;
 error_log /var/log/nginx/example.error_log crit;



About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!