nginx+lua+redis处理access日志

#Lua

local IP = "127.0.0.1"
local PORT = "6379"
local TOPIC = "access_log_audit"
local DB = '0'
local TIMEOUT = 1000

local function close_redis(red)
    if not red then
        return
    end
    -- 释放连接(连接池实现),毫秒
    local pool_max_idle_time = 10000 
    -- 连接池大小
    local pool_size = 100 
    local ok, err = red:set_keepalive(pool_max_idle_time, pool_size)
    local log = ngx_log
    if not ok then
        log(ngx_ERR, "set redis keepalive error : ", err)
    end
end


local function guid()
    local seed={'e','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}
    local tb={}
    for i=1,32 do
        table.insert(tb,seed[math.random(1,16)])
    end
    local sid=table.concat(tb)
    return string.format('%s-%s-%s-%s-%s',
        string.sub(sid,1,8),
        string.sub(sid,9,12),
        string.sub(sid,13,16),
        string.sub(sid,17,20),
        string.sub(sid,21,32)
    )
end

local redis = require('resty.redis')
local red = redis.new()

red:set_timeout(TIMEOUT)


local ok, error = red:connect(IP, PORT)

if not ok then
    return close_redis(red)
end

red:select(DB)

----------------------------------------------------------
local cjson = require('cjson')
local access_log = {}

access_log.headers = ngx.req.get_headers()
access_log.method = ngx.req.get_method()

local get_uri_args, err = ngx.req.get_uri_args()
access_log.get_uri_args = get_uir_args


if access_log.method == 'POST' then
    --access_log.get_post_args = get_post_args
    local get_post_args, error = ngx.req.get_post_args(0)
    access_log.get_post_args = get_post_args

local args, err = ngx.req.get_post_args()

         if err == "truncated" then
             -- one can choose to ignore or reject the current request here
         end

         if not args then
             ngx.say("failed to get post args: ", err)
             return
         end
         for key, val in pairs(args) do
             if type(val) == "table" then
                 --ngx.say(key, ": ", table.concat(val, ", "))
         access_log[key] = val
             else
                 --ngx.say(key, "|||::|||", val)
         access_log[key] = val
             end
         end

end 


----------------------------------------------------------

local msg = {}
msg.msg = cjson.encode(access_log) 
msg.biz = TOPIC
msg.priority = 2 
msg.id = guid() 
msg.msgt = 2

red:lpush( TOPIC, cjson.encode(msg)); 

close_redis(red)
 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值