access-log configuration custom-log error-log log-format logging monitoring nginx web-server

Monitoring : How to customize the error log in nginx?

Well, recently I came around a task in which I had to format the error log for nginx web server. I googled and I managed to use log_format directive to format access logs. Being lazy, I went for the same way to customize error log(I did it on live machine) and bang. It was giving error, and I just couldn’t believe why it won’t work as it was, a while ago, and now it it isn’t. After some time I realized, that there is difference in type of logs. It worked for access logs but not for error logs.

I then looked in detail, that, it indeed works for only for access logs and we can not customize the error logs in nginx.

Yes, I was puzzled when I saw following.


I was like what to do now.

Then I thought wait, I have a work around.

When we go through back, we note that, 1- we can format access logs, 2-we know that we have a directive called error_page, so why not create access log only when error occurs. Yes this is the work around.

This is how we can do it.

http {
  log_format custom_combined "...";
  server {
    error_page 50x @create_custom_error50x;
    location @create_custom_error50x {
      access_log path custom_combined;
      return 50x;


1 – log_format defines a format for the logs in http context.

2 – error_page directive internally redirect to create_custom_error50x named location on 50x error.

3 – inside create_custom_error50x location we create formatted access log using access_log directive.

4 – it returns the respective error(otherwise it will 404 error and we won’t know the error type occured) using return directive.

So, we can similarly write different location blocks and error_page statements for different errors. If the error code doesn’t matter, then all of them combined as well.


Links : The same search result in screenshot with one more answer.

Read about log_format, error_page.