2012-04-06 28 views
2

如何爲nginx設置自定義日誌格式,以便請求得到解析並將其部分分別記錄?使用nginx對日誌解析的請求

我們提供一個圖片文件來計算郵件打開。圖片的網址有所不同,但遵循以下規則:

http://www.server.com/counter/XXXXX/YYYYY/dailymail.gif 

XXXXX - 電子郵件活動的ID; YYYYY - 收件人ID。

有一個單獨的日誌/counter的位置,我想給喜歡

XXXXX YYYYY DATETIME 

位置部分看起來格式像

location ~* ^counter/([0-9]+)/([^/]+)/dailymail\.gif$ { 
     access_log /var/log/mailopened.log 
     alias /var/www/site.com/1x1.gif?cid=$1&uid=$2&type=daily; 
    } 

所以我在變量值$ 1和$ 2, 。我如何以日誌格式使用它們?

回答

5

log_format指令只允許在http級別,因此您必須根據其他變量來定義它,例如,

http { 
    log_format tracking "$xxxx $yyyy $time_local"; 

後來,在你的位置,只需設置這些變量並登錄tracking格式:

location ~* ^counter/([0-9]+)/([^/]+)/dailymail\.gif$ { 
    set $xxxx $1; 
    set $yyyy $2; 
    access_log /var/log/mailopened.log tracking; 
    alias /var/www/site.com/1x1.gif?cid=$1&uid=$2&type=daily; 
} 

隨着最新版本的Nginx和PCRE庫是可能的省略set電話和明確命名捕獲location(感謝@kolbyjack):

location ~* ^counter/(?<xxxx>[0-9]+)/(?<yyyy>[^/]+)/dailymail\.gif$ { 
    access_log /var/log/mailopened.log tracking; 
    alias /var/www/site.com/1x1.gif?cid=$1&uid=$2&type=daily; 
} 
+1

對於任何新版本的nginx的,你可以命名捕獲和使用'升跳過集通話ocation〜* ^/counter /(? [0-9] +)/(? [^ /] +)/ dailymail.gif $ {' – kolbyjack 2012-04-06 11:35:36

+0

好抓! PCRE版本也是相關的 - 你可能有最新的Nginx和舊的PCRE .. – 2012-04-06 13:03:23

+0

好點。用舊的pcre,你需要用'?P <'而不是'?<' – kolbyjack 2012-04-06 13:51:17