nginx_http_log

Overview

nginx supports two kinds of log, one is error log, the other is access log, error log can happen at any time when process request, but access log only happens when a request is finalized, once a time.

log type

error log

To write an error log, you need to enable it firstly by logging to a file or to syslog

1
2
# write error log to a particular file
error_log /var/log/error.log info;

later on in your source code, call ngx_log_error() with info that you want to write, more details LOG API

add connection and http meta when writing error log
In most case, we’re processing http request, we want to add request metadata when writing log, nginx provides log handler for this, when log instance is used, handler is called automatically to add extra info, save your time to write that repeated info.

such handler is called only for non DEBUG log, most used when error happens(ngx_log_error())

client connection

1
2
3
4
5
6
// when call ngx_log_error(log_level, c->log, ...); ngx_http_log_error is called by ngx_log_error_core if log_level is NOT DEBUG
c->log->handler = ngx_http_log_error;
r->log_handler = ngx_http_log_error_handler;
/* ngx_http_log_error: add client and server info
* ngx_http_log_error_handler: add request_line, Host header, upstream info
*/

access log

For each request, there is only one access log which is written at last when request is finalized, by default access_log is enabled with specific format, but you can change to any format you want.

1
2
3
4
5
6
7
8
http  {
# default access log format
# "$remote_addr - $remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent"

log_format access_log_format 'Client.Ip: "$remote_addr", Client.Port: "$remote_port"';
# use predefined format access_log_format from above
access_log /var/log/nginx-access.log access_log_format;
}

inside
access log is an NGX_HTTP_LOG_PHASE handler, which is called when request is freed ngx_http_free_request()->ngx_http_log_request(), ngx_http_log_request() calls handlers of NGX_HTTP_LOG_PHASE, access log handler ngx_http_log_handler() is one which writes access log to file.