前言
群里有朋友想切换nginx 0.7的版本到1.2+的版本,在0.7的版本中他们改了源码,使得访问日志输出的时间格式从[08/Mar/2013:09:30:58 +0800]变成了2013-03-08 12:21:03。说是在修改1.2+版本的时候格式就变乱了,格式一直不对,刚好有人@我,我说就帮忙看下。
须知
nginx log日志格式的话,无非是在src/core/nginx_times.c和src/http/modules/ngx_http_log_module.c 这两个文件中做修改。
nginx.conf 的默认日志格式中的时间格式使用$time_local去指定的,这是刷到acces.log中的时间格式是[08/Mar/2013:09:30:58 +0800]
日期格式更改
一.去下了个目前最新稳定版
nginx-1.2.7 ,打开nginx_http_log_module.c 查找到time_local,可以看到
{ ngx_string("time_local"), sizeof("28/Sep/1970:12:00:00 +0600") - 1,
ngx_http_log_time },
{ ngx_string("time_iso8601"), sizeof("1970-09-28T12:00:00+06:00") - 1,
在1.2.7版本中有个time_iso8601的变量,和目标格式很接近了,
更改1:
{ ngx_string("time_iso8601"), sizeof("1970-09-28T12:00:00+06:00") - 1,
=》
{ ngx_string("time_iso8601"), sizeof("1970-09-28 12:00:00") - 1,
更改nginx.conf配置为:
log_format main '$remote_addr - $remote_user $time_iso8601 "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
重编译后,启动,curl "localhost" 看刷log,还是不对。
二.打开ngx_times.c 查找 iso8601
看到第一处:
static u_char cached_http_log_iso8601[NGX_TIME_SLOTS]
[sizeof("1970-09-28T12:00:00+06:00")];
更改2:
[sizeof("1970-09-28T12:00:00+06:00")];
=》
[sizeof("1970-09-28 12:00:00")];
看到第二处:
ngx_cached_http_log_iso8601.len = sizeof("1970-09-28T12:00:00+06:00") - 1;
更改2:
ngx_cached_http_log_iso8601.len = sizeof("1970-09-28T12:00:00+06:00") - 1;
=》
ngx_cached_http_log_iso8601.len = sizeof("1970-09-28 12:00:00") - 1;
看到第三处:
p3 = &cached_http_log_iso8601[slot][0];
(void) ngx_sprintf(p3, "%4d-%02d-%02dT%02d:%02d:%02d%c%02d:%02d",
tm.ngx_tm_year, tm.ngx_tm_mon,
tm.ngx_tm_mday, tm.ngx_tm_hour,
tm.ngx_tm_min, tm.ngx_tm_sec,
tp->gmtoff < 0 ? '-' : '+',
ngx_abs(tp->gmtoff / 60), ngx_abs(tp->gmtoff % 60));
更改3:
(void) ngx_sprintf(p3, "%4d-%02d-%02dT%02d:%02d:%02d%c%02d:%02d",
tm.ngx_tm_year, tm.ngx_tm_mon,
tm.ngx_tm_mday, tm.ngx_tm_hour,
tm.ngx_tm_min, tm.ngx_tm_sec,
tp->gmtoff < 0 ? '-' : '+',
ngx_abs(tp->gmtoff / 60), ngx_abs(tp->gmtoff % 60));
=》
(void) ngx_sprintf(p3, "%4d-%02d-%02d %02d:%02d:%02d",
tm.ngx_tm_year, tm.ngx_tm_mon,
tm.ngx_tm_mday, tm.ngx_tm_hour,
tm.ngx_tm_min, tm.ngx_tm_sec);
ok,重新编译,启动,curl "localhost",查看acees.log 就可以看到
127.0.0.1 - - 2013-03-08 12:21:03 "GET / HTTP/1.1" 200 612
总结
一般很少去改动nginx源码,基本做开发也只是做nginx的http模块,这也是难得一次经验,还比较顺利。