用lua重写nginx日志

此处用到lua-nginx-module openresty是自带的~ nginx需要安装库

文档:https://github.com/openresty/lua-nginx-module

备注: 由于此处需要记录同类型的两个日志(visit_log.log和share_log.log)所以用到 ngx.var.conf进行传参~ 具体赋值方法如下:

Nginx配置

location /visit.gif {
    set $conf 'visit';
    content_by_lua_file conf/data.lua;
}

location /share.gif {
    set $conf 'share';
    content_by_lua_file conf/data.lua;
}

data.lua

local file_name
local conf = ngx.var.conf -- 在外部设置了ngx.var.conf变量 在里面读出来
if(conf == 'visit')
then
    file_name = '/usr/local/openresty/nginx/logs/visit_log.log'
elseif(conf == 'share')
then
    file_name = '/usr/local/openresty/nginx/logs/share_log.log'
end

--[[
-- 写文件
-- fileName 文件名
-- content 写入内容
--]]
function write_content(fileName, content)
        local  f = assert(io.open(fileName,'a'))
        f:write(content)
        f:close()
end

-- 打开request body的读取
ngx.req.read_body()

local s
local extend = '&ip='..ngx.var.remote_addr..'&userAgent='..ngx.req.get_headers()["User-Agent"]..'\n' -- 将要扩展的在这里拼接

--判断是POST还是GET
if(ngx.req.get_method() == 'POST')
then
    s = ngx.var.request_body..extend
    if (nil ~= s)
    then
        -- 写入对应文件
        write_content(file_name, s)
    end
else
    s = ngx.var.args..extend
    if (nil ~= s)
    then
        write_content(file_name, s)
    end
end

转载于:https://my.oschina.net/mHUMTSy9311/blog/1925098

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值