目标:收集用户日志
流程:
- 浏览器端get方法将数据传到nginx服务
- nginx收集到数据,执行内嵌lua脚本,访问redis,根据token获得用户id
- 将日志信息存入文件
1、nginx安装,参见:http://www.cnblogs.com/unreal/articles/7739290.html
2、安装lua_nginx_module 模块
(略,自行百度)
3、编辑nginx.conf配置文件
[root@master1 conf]# cat /usr/local/nginx/conf/nginx.conf
worker_processes ;
error_log logs/error.log;
pid logs/nginx.pid; events {
worker_connections ;
} http {
include mime.types;
default_type application/octet-stream; log_format log_format '$remote_addr^A$msec^A$http_host^A$request_uri';
log_format log_token '$uid_by_token^A$remote_addr^A$msec^A$http_host^A$request_uri'; sendfile on;
#tcp_nopush on; #keepalive_timeout ;
keepalive_timeout ;
lua_package_path "/usr/local/nginx/lua/lua-resty-redis/lib/?.lua;;";
server {
listen ;
server_name master1 0.0.0.0; location /log {
allow 192.168.8.0/;
deny all;
default_type 'text/html';
access_log logs/access.log log_format;
content_by_lua '
ngx.say("success")
';
} location /do {
#lua_code_cache off;
set $uid_by_token '';
default_type 'text/html';
rewrite_by_lua_file "conf/do.lua";
access_log logs/access.log log_token;
}
}
}
4、编写do.lua文件
[root@master1 ~]# vim /usr/local/nginx/conf/do.lua --redis ip port pwd
local ip = '192.168.0.8'
local port =
local pwd = ""
local key_prefix = "Project:SsoToken:"
------------------ function get_uid(uinfo)
local uid = ''
if uinfo ~= ngx.null then
local pos, _ = string.find(uinfo, '"Id":')
if pos and pos> then
local left = string.sub(uinfo, pos, -)
local end_pos, _ = string.find(left, ",")
local line
if end_pos and end_pos> then
line = string.sub(left, , end_pos)
else
end_pos, _ = string.find(left, "}")
if end_pos and end_pos> then
line = string.sub(left, , end_pos)
end
end
line = string.sub(line, , -)
uid = string.gsub(line, "^%s*(.-)%s*$", "%1")
end
end
return uid
end local function close_redis(redis_instance)
if not redis_instance then
return
end
local ok,err = redis_instance:close();
end local token = ngx.var.arg_t
local redis = require("resty.redis");
local redis_instance = redis:new();
redis_instance:set_timeout()
local ok,err = redis_instance:connect(ip,port)
if not ok then
return close_redis(redis_instance);
end local auth,err = redis_instance:auth(pwd);
local uinfo, err = redis_instance:get(key_prefix .. token)
if not uinfo then
return close_redis(redis_instance)
end
close_redis(redis_instance) ngx.var.uid_by_token = get_uid(uinfo)
ngx.say('done')
5、测试
浏览器访问输入访问地址:http://master1/do?t=99b61873a98742a3a29a4a6d64bc043f&en=pv&ct=1521163377&ver=1&pl=pc
服务器查看日志:
[root@master1 nginx]# tail -f logs/access.log
^A192.168.8.^A1521181427.^Amaster1^A/do?t=99b61873a98742a3a29a4a6d64bc043f&en=pv&ct=&ver=&pl=pc
^A192.168.8.^A1521181462.^Amaster1^A/do?t=99b61873a98742a3a29a4a6d64bc043f&en=pv&ct=&ver=&pl=pc
^A192.168.8.^A1521187161.^Amaster1^A/do?t=99b61873a98742a3a29a4a6d64bc043f&en=pv&ct=&ver=&pl=pc