8

Need some help in setting up nginx logs so that they are not duplicated.

My configuration is as following. What I would like to achieve is that all logs for say, http://example.com/app goes to file app.access.log and logs for rest of the site goes to file main.access.log

However, following configuration logs app logs to both, app.access.log and main.access.log.

server {

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


       location /app {
           access_log /var/log/nginx/app.access.log;
       }
}

Any idea how to fix this?

mesibo
  • 3,970
  • 6
  • 25
  • 43

2 Answers2

2

You could use a negation regexp to intercept all request NOT directed to app, and define there the access_log directive. Then define the other location for app

location ~ ^((?!app).)*$ {
        access_log /var/log/nginx/not-an-app.access.log;
   }

location /app { 
       access_log /var/log/nginx/app.access.log;
   }

I think it's a bit of a stretch though, and i would test the hell out of this before putting it in production.

Andrea Golin
  • 3,259
  • 1
  • 17
  • 23
  • You do not need the negation regular expression, as `location /` will match any URI that does not match `/app`. For a non-trivial configuration with more than two `location` blocks, you could nest all of the other `location` blocks under `location /`. – Richard Smith Oct 12 '18 at 08:25
0

The access_log directive includes an if=condition which can be used to control logging.

For example:

map $request_uri $loggable {
    ~^/app  0;
    default 1;
}
server {
    access_log /var/log/nginx/main.access.log if=$loggable;
    ...
}

See this document for details.

The alternative is to log everything together and split it into two separate files later using grep.


Inspired by @Andrea's solution, you could also use this pattern:

server {
    location / {
        access_log /var/log/nginx/main.access.log;

        location /foo { ... }
        location /bar { ... }
        ...
    }
    location /app {
        access_log /var/log/nginx/app.access.log;
    }
}

So the top level has just two top level location blocks, and all other location blocks are nested within the default `location.

Richard Smith
  • 45,711
  • 6
  • 82
  • 81