这篇文章仅适合有一定nginx配置基础的人观看


开源插件地址 : https://github.com/Lax/ngx_http_accounting_module

1 安装方法,下载nginx源代码,解压到 /path/to/nginx-src/ ,下载 accounting 解压到ngx_http_accounting_module

cd /path/to/nginx-src/
./configure --add-module=/path/to/ngx_http_accounting_module
make && make install


2 配置方法

http{
 http_accounting  on;   # 打开accunting 功能
 ...
 server {
   http_accounting_id  accounting_id_str;   # 设置accounting id,对整个sever
   ...
   location / {
     http_accounting_id  accounting_id_str;    # 设置基于路径记录的accounting_id 这样设置会根据该id统计流量信息
     ...
   }
 }
}


3 测试

启动nginx后,日志会记录到系统日志,/var/log/message,类似

May 17 15:00:19 localhost NgxAccounting: pid:12145|from:1368773989|to:1368774019|accounting_id:test.test.com|requests:1|bytes_out:167|404:1
May 17 15:00:49 localhost NgxAccounting: pid:12145|from:1368774019|to:1368774049|accounting_id:test.test.com|requests:1|bytes_out:167|404:1
May 17 15:01:19 localhost NgxAccounting: pid:12145|from:1368774049|to:1368774079|accounting_id:test.test.com|requests:1|bytes_out:167|404:1


3 配置独立文件存储日志

echo "syslog.*                /var/log/syslog" >>  /etc/syslog.conf
service syslog restart


4 测试

启动nginx后,访问网站,可以看到/var/log/syslog 有类似的输出

May 17 17:39:15 localhost NgxAccounting: pid:19056|from:1368783525|to:1368783555|accounting_id:test.test.com|requests:30|bytes_out:882066|200:30
May 17 17:57:45 localhost NgxAccounting: pid:19056|from:1368784635|to:1368784665|accounting_id:test.test.com|requests:1|bytes_out:4087|200:1
May 17 18:21:15 localhost NgxAccounting: pid:19056|from:1368786045|to:1368786075|accounting_id:test.test.com|requests:2|bytes_out:507617|200:2
May 17 18:23:45 localhost NgxAccounting: pid:19056|from:1368786195|to:1368786225|accounting_id:zxycdn.5711.com|requests:1|bytes_out:727|403:1
May 17 18:24:15 localhost NgxAccounting: pid:19056|from:1368786225|to:1368786255|accounting_id:test.test.com|requests:1|bytes_out:1989|200:1