SEO需要对accesslog进行分析,其中有需要把时间转换为秒再进行判断


nginx有两个日志格式,分别是$time_local和$time_iso8601,现在线上使用的是$time_local

两个格式都不符合要求,想要的格式是“2013-08-05 11:50:01”,再通过date -d "2013-08-05 11:50:01" +%s来转换为秒


网上搜索,可以通过修改nginx的源码来进行修改日志格式,具体操作如下:

1、src/http/modules/ngx_http_log_module.c  

    { 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,


2、src/core/ngx_times.c

看到第一处:

static u_char            cached_http_log_iso8601[NGX_TIME_SLOTS]

[sizeof("1970-09-28T12:00:00+06:00")]; 更改1: [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,修改好之后,重新编译


再把accesslog的日志格式定义为

   log_format  main  '$remote_addr - $time_iso8601 [$time_local] "$request" '

                     '$status $body_bytes_sent "$http_referer" '

                     '"$http_user_agent" "$http_x_forwarded_for"';


访问,查看日志内容:

192.168.3.170 - 2013-08-05 11:50:01 [05/Aug/2013:11:50:01 +0800] "GET /favicon.ico HTTP/1.1" 404 581 "-" "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Maxthon/4.0.6.2000 Chrome/26.0.1410.43 Safari/537.1" "-"


ok,搞定