1. 极安网首页
  2. 网络安全技术

nginx日志模块源码分析

nginx日志模块源码分析-极安网

ngx_http_log_module简介

ngx_http_log_module模块按指定的格式写访问日志。

请求在处理结束时,会按请求路径的配置上下文记访问日志。 如果在请求处理期间产生了内部跳转(参考另一篇nginx跳转讲述), 请求结束时的路径可能不同于原始的请求路径。

官方模块使用说明http://nginx.org/en/docs/http/ngx_http_log_module.html

配置实例说明

在nginx.conf中相关的配置指令为:

log_format                  proxyformat "$time_iso8601 $remote_addr:$remote_port $server_addr:$server_port $upstream_addr $request_time $upstream_response_time $status $upstream_status $request_leng

th $body_bytes_sent \"$request_method $scheme://$http_host$request_uri $server_protocol\" \"$http_referer\" \"$http_user_agent\"";

access_log                  syslog:facility=local3,severity=info,server=127.0.0.1:514,tag=tengine proxyformat;

log_format gzip '$remote_addr - $remote_user [$time_local] '
                '"$request" $status $bytes_sent '
                '"$http_referer" "$http_user_agent" "$gzip_ratio"';

access_log /spool/logs/nginx-access.log gzip buffer=32k;
语法格式: access_logpath [format [buffer=size]];
access_logoff;
默认:
access_log logs/access.log combined;
配置生效空间上下文: httpserverlocationif in locationlimit_except

为访问日志设置路径,格式和缓冲区大小(nginx访问日志支持缓存)。

在同一个配置层级里可以指定多个日志。

特定值off会取消当前配置层级里的所有access_log指令。

如果没有指定日志格式则会使用预定义的combined格式。

缓冲区的大小不能超过磁盘文件原子性写入的大小。

对于FreeBSD来说缓冲区大小是无限制的。

日志文件的路径可以包含变量(0.7.6+), 但此类日志存在一些限制:

应该拥有在目录里创建文件的权限。

写缓冲无效。

每条日志写入都会打开和关闭文件。频繁使用的文件描述符可以存储在缓存中, 在open_log_file_cache指令的valid参数指定的时间里,写操作能持续写到旧文件。

每次日志写入的操作都会检查请求的根目录是否存在(即ngx root配置), 如果不存在则日志不会被创建。 在一个层级里同时指定root和access_log是个不错的办法:

server {
    root       /spool/vhost/data/$host;
    access_log /spool/vhost/logs/$host;
    ...
}
语法: log_formatname string ...;
默认:
log_format combined "...";
配置生效空间上下文: http

指定日志的格式。

日志格式允许包含普通变量和只在日志写入时存在的变量:

$body_bytes_sent
发送给客户端的字节数,不包括响应头的大小; 该变量与Apache模块mod_log_config里的“%B”参数兼容。
$bytes_sent
发送给客户端的总字节数。
$connection
连接的序列号。
$connection_requests
当前通过一个连接获得的请求数量。
$msec
日志写入时间。单位为秒,精度是毫秒。
$pipe
如果请求是通过HTTP流水线(pipelined)发送,pipe值为“p”,否则为“.”。

$request_length

请求的长度(包括请求行,请求头和请求正文)。

$request_time

请求处理时间,单位为秒,精度毫秒; 从读入客户端的第一个字节开始,直到把最后一个字符发送给          客户端后进行日志写入为止。

$status

响应状态。

$time_iso8601

ISO8601标准格式下的本地时间。

$time_local

通用日志格式下的本地时间。

发送给客户端的响应头拥有"sent_http_"前缀,比如$sent_http_content_range。

配置始终包含预先定义的"combined"日志格式:

log_format combined '$remote_addr - $remote_user [$time_local] '
                    '"$request" $status $body_bytes_sent '
                    '"$http_referer" "$http_user_agent"';
语法: open_log_file_cachemax=N [inactive=time] [min_uses=N] [valid=time];
open_log_file_cacheoff;
默认:
open_log_file_cache off;
配置生效空间上下文: httpserverlocation

定义一个缓存,用来存储频繁使用的文件名中包含变量的日志文件描述符。 该指令包含以下参数:

max
设置缓存中描述符的最大数量;如果缓存被占满,最近最少使用(LRU)的描述符将被关闭。
inactive
设置缓存文件描述符在多长时间内没有被访问就关闭; 默认为10秒。
min_uses
设置在inactive参数指定的时间里, 最少访问多少次才能使文件描述符保留在缓存中;默认为1。
valid
设置一段用于检查超时后文件是否仍以同样名字存在的时间; 默认为60秒。
off
禁用缓存。

使用实例:

open_log_file_cache max=1000 inactive=20s valid=1m min_uses=2;

nginx log_module源码分析

先关注log模块的初始化

static ngx_http_module_t  ngx_http_log_module_ctx = {

NULL,                                  /* preconfiguration */

ngx_http_log_init,               /* postconfiguration */

ngx_http_log_create_main_conf,    /* create main configuration */

NULL,                                  /* init main configuration */

NULL,                                  /* create server configuration */

NULL,                                  /* merge server configuration */

ngx_http_log_create_loc_conf,       /* create location configuration */

ngx_http_log_merge_loc_conf       /* merge location configuration */

};

static void *

ngx_http_log_create_main_conf(ngx_conf_t *cf)

{

ngx_http_log_main_conf_t  *conf;

ngx_http_log_fmt_t  *fmt;

conf = ngx_pcalloc(cf->pool, sizeof(ngx_http_log_main_conf_t));

if (conf == NULL) {

return NULL;

}

// 初始化format

if (ngx_array_init(&conf->formats, cf->pool, 4, sizeof(ngx_http_log_fmt_t)) != NGX_OK)

{

return NULL;

}

return conf;

}

static ngx_int_t ngx_http_log_init(ngx_conf_t *cf)

{

// 这块有判断是否使用默认的combine的逻辑,在tengine中,自定义了一波,所以不care

// 将handler加入log阶段

cmcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_core_module);

h = ngx_array_push(&cmcf->phases[NGX_HTTP_LOG_PHASE].handlers);

if (h == NULL) {

return NGX_ERROR;

}

*h = ngx_http_log_handler;

return NGX_OK;

}

而在log_format指令的处理函数中,将这个fmt给保存下来

static char * ngx_http_log_set_format(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)

{

// 获取loc_main_conf

ngx_http_log_main_conf_t *lmcf = conf;

// 初始化fmt

fmt = lmcf->formats.elts;

fmt = ngx_array_push(&lmcf->formats);

if (fmt == NULL) {

return NGX_CONF_ERROR;

}

// 赋值name

fmt->name = value[1];

// 初始化flushes和ops

fmt->flushes = ngx_array_create(cf->pool, 4, sizeof(ngx_int_t));

if (fmt->flushes == NULL) {

return NGX_CONF_ERROR;

}

fmt->ops = ngx_array_create(cf->pool, 16, sizeof(ngx_http_log_op_t));

if (fmt->ops == NULL) {

return NGX_CONF_ERROR;

}

// 最后把整个日志格式编译

return ngx_http_log_compile_format(cf, fmt->flushes, fmt->ops, cf->args, 2);

}

static char * ngx_http_log_compile_format(ngx_conf_t *cf, ngx_array_t *flushes,ngx_array_t *ops, ngx_array_t *args, ngx_uint_t s)

{

// 遍历所有的args

for ( /* void */ ; s < args->nelts; s++) {

// 在已有的ngx_http_log_vars中看有没有指定的日志格式

for (v = ngx_http_log_vars; v->name.len; v++) {

if (v->name.len == var.len && ngx_strncmp(v->name.data, var.data, var.len) == 0)

{

// 将对应的方法,长度赋值给对应op,等待写入

op->len = v->len;

op->getlen = NULL;

op->run = v->run;

op->data = 0;

goto found;

}

}

// 没有的话则调用该函数

if (ngx_http_log_variable_compile(cf, op, &var) != NGX_OK) {

return NGX_CONF_ERROR;

}

if (len) {

op->len = len;

op->getlen = NULL;

// 如果长度小的话,就直接用data来记录

if (len <= sizeof(uintptr_t)) {

op->run = ngx_http_log_copy_short;

op->data = 0;

// 记录data

while (len--) {

op->data <<= 8;

op->data |= data[len];

}

// 比较长的话,记录成指针来指向,函数也是获取指针来进行获取值

} else {

op->run = ngx_http_log_copy_long;

p = ngx_pnalloc(cf->pool, len);

if (p == NULL) {

return NGX_CONF_ERROR;

}

ngx_memcpy(p, data, len);

op->data = (uintptr_t) p;

}

}

}

static ngx_int_t ngx_http_log_variable_compile(ngx_conf_t *cf, ngx_http_log_op_t *op, ngx_str_t *value)

{

ngx_int_t  index;

index = ngx_http_get_variable_index(cf, value);

op->len = 0;

op->getlen = ngx_http_log_variable_getlen;

op->run = ngx_http_log_variable;

op->data = index;

}

// 而这些可以进入日志中的参数,则是在core_preconfiguration函数中的ngx_http_variables_add_core_vars函数

ngx_int_t ngx_http_variables_add_core_vars(ngx_conf_t *cf)

{

cmcf->variables_keys = ngx_pcalloc(cf->temp_pool,

sizeof(ngx_hash_keys_arrays_t));

for (cv = ngx_http_core_variables; cv->name.len; cv++) {

v = ngx_palloc(cf->pool, sizeof(ngx_http_variable_t));

if (v == NULL) {

return NGX_ERROR;

}

*v = *cv;

rc = ngx_hash_add_key(cmcf->variables_keys, &v->name, v, NGX_HASH_READONLY_KEY);

if (rc == NGX_OK) {

continue;

}

if (rc == NGX_BUSY) {

ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "conflicting variable name \"%V\"", &v->name);

}

return NGX_ERROR;

}

接下来可以看下整个的ngx_http_core_variables

static ngx_http_variable_t  ngx_http_core_variables[] = {

{ ngx_string("http_host"), NULL, ngx_http_variable_header,

offsetof(ngx_http_request_t, headers_in.host), 0, 0 },

{ ngx_string("http_user_agent"), NULL, ngx_http_variable_header,

offsetof(ngx_http_request_t, headers_in.user_agent), 0, 0 },

{ ngx_string("http_referer"), NULL, ngx_http_variable_header,

offsetof(ngx_http_request_t, headers_in.referer), 0, 0 },

#if (NGX_HTTP_GZIP)

{ ngx_string("http_via"), NULL, ngx_http_variable_header,

offsetof(ngx_http_request_t, headers_in.via), 0, 0 },

#endif

#if (NGX_HTTP_X_FORWARDED_FOR)

{ ngx_string("http_x_forwarded_for"), NULL, ngx_http_variable_headers,

offsetof(ngx_http_request_t, headers_in.x_forwarded_for), 0, 0 },

#endif

{ ngx_string("http_cookie"), NULL, ngx_http_variable_cookies,

offsetof(ngx_http_request_t, headers_in.cookies), 0, 0 },

{ ngx_string("content_length"), NULL, ngx_http_variable_content_length,

0, 0, 0 },

{ ngx_string("content_type"), NULL, ngx_http_variable_header,

offsetof(ngx_http_request_t, headers_in.content_type), 0, 0 },

{ ngx_string("host"), NULL, ngx_http_variable_host, 0, 0, 0 },

{ ngx_string("binary_remote_addr"), NULL,

ngx_http_variable_binary_remote_addr, 0, 0, 0 },

{ ngx_string("remote_addr"), NULL, ngx_http_variable_remote_addr, 0, 0, 0 },

{ ngx_string("remote_port"), NULL, ngx_http_variable_remote_port, 0, 0, 0 },

{ ngx_string("proxy_protocol_addr"), NULL,

ngx_http_variable_proxy_protocol_addr, 0, 0, 0 },

{ ngx_string("server_addr"), NULL, ngx_http_variable_server_addr, 0, 0, 0 },

{ ngx_string("server_port"), NULL, ngx_http_variable_server_port, 0, 0, 0 },

{ ngx_string("server_protocol"), NULL, ngx_http_variable_request,

offsetof(ngx_http_request_t, http_protocol), 0, 0 },

{ ngx_string("scheme"), NULL, ngx_http_variable_scheme, 0, 0, 0 },

{ ngx_string("https"), NULL, ngx_http_variable_https, 0, 0, 0 },

{ ngx_string("full_request"), NULL, ngx_http_variable_full_request,

0, 0, 0 },

{ ngx_string("normalized_request"), NULL, ngx_http_variable_normalized_request,

0, 0, 0 },

{ ngx_string("request_uri"), NULL, ngx_http_variable_request,

offsetof(ngx_http_request_t, unparsed_uri), 0, 0 },

{ ngx_string("raw_uri"), NULL, ngx_http_variable_request,

offsetof(ngx_http_request_t, raw_uri), 0, 0 },

{ ngx_string("uri"), NULL, ngx_http_variable_request,

offsetof(ngx_http_request_t, uri),

NGX_HTTP_VAR_NOCACHEABLE, 0 },

{ ngx_string("document_uri"), NULL, ngx_http_variable_request,

offsetof(ngx_http_request_t, uri),

NGX_HTTP_VAR_NOCACHEABLE, 0 },

{ ngx_string("request"), NULL, ngx_http_variable_request_line, 0, 0, 0 },

{ ngx_string("document_root"), NULL,

ngx_http_variable_document_root, 0, NGX_HTTP_VAR_NOCACHEABLE, 0 },

{ ngx_string("realpath_root"), NULL,

ngx_http_variable_realpath_root, 0, NGX_HTTP_VAR_NOCACHEABLE, 0 },

{ ngx_string("query_string"), NULL, ngx_http_variable_request,

offsetof(ngx_http_request_t, args),

NGX_HTTP_VAR_NOCACHEABLE, 0 },

{ ngx_string("args"),

ngx_http_variable_set_args,

ngx_http_variable_request,

offsetof(ngx_http_request_t, args),

NGX_HTTP_VAR_CHANGEABLE|NGX_HTTP_VAR_NOCACHEABLE, 0 },

{ ngx_string("is_args"), NULL, ngx_http_variable_is_args,

0, NGX_HTTP_VAR_NOCACHEABLE, 0 },

{ ngx_string("request_filename"), NULL,

ngx_http_variable_request_filename, 0,

NGX_HTTP_VAR_NOCACHEABLE, 0 },

{ ngx_string("server_name"), NULL, ngx_http_variable_server_name, 0, 0, 0 },

{ ngx_string("request_method"), NULL,

ngx_http_variable_request_method, 0,

NGX_HTTP_VAR_NOCACHEABLE, 0 },

{ ngx_string("remote_user"), NULL, ngx_http_variable_remote_user, 0, 0, 0 },

{ ngx_string("bytes_sent"), NULL, ngx_http_variable_bytes_sent,

0, 0, 0 },

{ ngx_string("body_bytes_sent"), NULL, ngx_http_variable_body_bytes_sent,

0, 0, 0 },

{ ngx_string("pipe"), NULL, ngx_http_variable_pipe,

0, 0, 0 },

{ ngx_string("request_completion"), NULL,

ngx_http_variable_request_completion,

0, 0, 0 },

{ ngx_string("request_body"), NULL,

ngx_http_variable_request_body,

0, 0, 0 },

{ ngx_string("request_body_file"), NULL,

ngx_http_variable_request_body_file,

0, 0, 0 },

{ ngx_string("request_length"), NULL, ngx_http_variable_request_length,

0, NGX_HTTP_VAR_NOCACHEABLE, 0 },

{ ngx_string("request_time"), NULL, ngx_http_variable_request_time,

0, NGX_HTTP_VAR_NOCACHEABLE, 0 },

{ ngx_string("status"), NULL,

ngx_http_variable_status, 0,

NGX_HTTP_VAR_NOCACHEABLE, 0 },

{ ngx_string("sent_http_content_type"), NULL,

ngx_http_variable_sent_content_type, 0, 0, 0 },

{ ngx_string("sent_http_content_length"), NULL,

ngx_http_variable_sent_content_length, 0, 0, 0 },

{ ngx_string("sent_http_location"), NULL,

ngx_http_variable_sent_location, 0, 0, 0 },

{ ngx_string("sent_http_last_modified"), NULL,

ngx_http_variable_sent_last_modified, 0, 0, 0 },

{ ngx_string("sent_http_connection"), NULL,

ngx_http_variable_sent_connection, 0, 0, 0 },

{ ngx_string("sent_http_keep_alive"), NULL,

ngx_http_variable_sent_keep_alive, 0, 0, 0 },

{ ngx_string("sent_http_transfer_encoding"), NULL,

ngx_http_variable_sent_transfer_encoding, 0, 0, 0 },

{ ngx_string("sent_http_cache_control"), NULL, ngx_http_variable_headers,

offsetof(ngx_http_request_t, headers_out.cache_control), 0, 0 },

{ ngx_string("limit_rate"), ngx_http_variable_request_set_size,

ngx_http_variable_request_get_size,

offsetof(ngx_http_request_t, limit_rate),

NGX_HTTP_VAR_CHANGEABLE|NGX_HTTP_VAR_NOCACHEABLE, 0 },

{ ngx_string("connection"), NULL,

ngx_http_variable_connection, 0, 0, 0 },

{ ngx_string("connection_requests"), NULL,

ngx_http_variable_connection_requests, 0, 0, 0 },

{ ngx_string("nginx_version"), NULL, ngx_http_variable_nginx_version,

0, 0, 0 },

{ ngx_string("hostname"), NULL, ngx_http_variable_hostname,

0, 0, 0 },

{ ngx_string("pid"), NULL, ngx_http_variable_pid,

0, 0, 0 },

{ ngx_string("msec"), NULL, ngx_http_variable_msec,

0, NGX_HTTP_VAR_NOCACHEABLE, 0 },

{ ngx_string("dollar"), NULL, ngx_http_variable_dollar,

0, 0, 0 },

{ ngx_string("host_comment"), NULL, ngx_http_variable_host_comment,

0, 0, 0 },

{ ngx_string("unix_time"), NULL, ngx_http_variable_unix_time,

0, NGX_HTTP_VAR_NOCACHEABLE, 0 },

{ ngx_string("year"), NULL, ngx_http_variable_year,

0, NGX_HTTP_VAR_NOCACHEABLE, 0 },

{ ngx_string("year2"), NULL, ngx_http_variable_year2,

0, NGX_HTTP_VAR_NOCACHEABLE, 0 },

{ ngx_string("month"), NULL, ngx_http_variable_month,

0, NGX_HTTP_VAR_NOCACHEABLE, 0 },

{ ngx_string("day"), NULL, ngx_http_variable_day,

0, NGX_HTTP_VAR_NOCACHEABLE, 0 },

{ ngx_string("hour"), NULL, ngx_http_variable_hour,

0, NGX_HTTP_VAR_NOCACHEABLE, 0 },

{ ngx_string("hour12"), NULL, ngx_http_variable_hour12,

0, NGX_HTTP_VAR_NOCACHEABLE, 0 },

{ ngx_string("minute"), NULL, ngx_http_variable_minute,

0, NGX_HTTP_VAR_NOCACHEABLE, 0 },

{ ngx_string("second"), NULL, ngx_http_variable_second,

0, NGX_HTTP_VAR_NOCACHEABLE, 0 },

{ ngx_string("time_iso8601"), NULL, ngx_http_variable_time_iso8601,

0, NGX_HTTP_VAR_NOCACHEABLE, 0 },

{ ngx_string("time_local"), NULL, ngx_http_variable_time_local,

0, NGX_HTTP_VAR_NOCACHEABLE, 0 },

{ ngx_string("time_http"), NULL, ngx_http_variable_time_http,

0, NGX_HTTP_VAR_NOCACHEABLE, 0 },

#if (NGX_HAVE_TCP_INFO)

{ ngx_string("tcpinfo_rtt"), NULL, ngx_http_variable_tcpinfo,

0, NGX_HTTP_VAR_NOCACHEABLE, 0 },

{ ngx_string("tcpinfo_rttvar"), NULL, ngx_http_variable_tcpinfo,

1, NGX_HTTP_VAR_NOCACHEABLE, 0 },

{ ngx_string("tcpinfo_snd_cwnd"), NULL, ngx_http_variable_tcpinfo,

2, NGX_HTTP_VAR_NOCACHEABLE, 0 },

{ ngx_string("tcpinfo_rcv_space"), NULL, ngx_http_variable_tcpinfo,

3, NGX_HTTP_VAR_NOCACHEABLE, 0 },

#endif

{ ngx_null_string, NULL, NULL, 0, 0, 0 }

};

这块是在ngx_http_variables_init_vars中初始化

ngx_int_t ngx_http_variables_init_vars(ngx_conf_t *cf)

{

cmcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_core_module);

v = cmcf->variables.elts;

key = cmcf->variables_keys->keys.elts;

for (i = 0; i < cmcf->variables.nelts; i++) {

for (n = 0; n < cmcf->variables_keys->keys.nelts; n++) {

av = key[n].value;

if (v[i].name.len == key[n].key.len && ngx_strncmp(v[i].name.data, key[n].key.data, v[i].name.len) == 0)

{

// 将get_handler和data赋值过来

v[i].get_handler = av->get_handler;

v[i].data = av->data;

}

原创文章,作者: Admin ,转载请注明出处:https://www.secvery.com/4248.html