使用Nginx记录已解析的请求 [英] Log parsed request with nginx
问题描述
如何为nginx设置自定义日志格式,以便解析请求并将其各个部分分别记录?
How to set a custom log format for nginx, so that request got parsed and its parts are logged separate?
我们提供图片文件来统计邮件的打开次数.图片的网址有所不同,但遵循以下规则:
We serve a picture file to count mail opens. The url to the picture varies, but follows the rule:
http://www.server.com/counter/XXXXX/YYYYY/dailymail.gif
XXXXX-电子邮件广告系列的ID; YYYYY-收件人ID.
XXXXX - id of email campaign; YYYYY - recipient id.
对于/counter
位置有一个单独的日志,我想给出类似的格式
There's a separate log for /counter
location, which I'd like to give a format like
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中有值.如何以日志格式使用它们?
So I have the values in variables $1 and $2. How can I use them in the log format?
推荐答案
log_format
指令仅在http
级别允许,因此您必须根据其他变量(例如
log_format
directive is allowed at http
level only, so you have to define it in terms of other variables, e.g.
http {
log_format tracking "$xxxx $yyyy $time_local";
稍后,在您所在的位置,只需设置以下变量并以tracking
格式登录即可:
Later, in your location, just set these variables and log in tracking
format:
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):
With recent versions of Nginx and PCRE library it's possible to omit set
calls and name the captures explicitly in location
(thanks to @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;
}
这篇关于使用Nginx记录已解析的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!