歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Lua非阻塞寫日志

Lua非阻塞寫日志

日期:2017/3/1 9:19:00   编辑:Linux編程

用nginx-lua搭的服務需要寫日志,一般采用nginx自帶的accesslog加logrotate腳本來實現,但是無法滿足一次請求需要寫多條日志的需求

之前用C和GO實現過類似的代碼,思路是主進程寫管道,子進程讀管道並交由apache-rotatelogs寫日志

這裡用Lua也實現了一下--

-- Rlog is an non-blocking logging based on pipe.
-- Rotatelogs of Apache is recommanded to be the output of pipe.
-- Before using Rlog, you should install luaposix.
--

local posix = require("posix")
local os = require("os")

-- input of pipe
local pipe_in

-- init rlog
-- @param pipe_cmd pipe operator and the reveiver command.
-- e.g. "| rotatelogs -l %Y%m%d%H.logfile 3600"
-- @return true when success, false when fail
local function init(pipe_cmd)
-- if already inited, do nothing
if pipe_in then return true end

-- if pipe_cmd is not start with pipe operator, return false
if string.sub(pipe_cmd, 1, 1) ~= "|" then return false end

-- create pipe
local pout, pin = posix.pipe()

-- fork process to execute cmd
if posix.fork() == 0 then
-- close stdin
io.close(io.stdin)

-- set output of pipe as stdin
posix.dup2(pout, posix.fileno(io.stdin))

-- close input and output of pipe
posix.close(pout)
posix.close(pin)

-- execute cmd
os.execute(string.sub(pipe_cmd, 2, -1))
end

-- get input of pipe
pipe_in = pin

-- close output of pipe
posix.close(pout)

return true
end

-- write log
local function log(log_str)
-- write log into pipe
posix.write(pipe_in, log_str .. "\n")
end

return {
init = init,
log = log
}

下邊是它的測試程序

local rlog = require("rlog")

-- init
ret = rlog.init("| rotatelogs -l %Y%m%d%H.log 3600")
if not ret then
print("init fail")
end

-- log
rlog.log("Hello Rlog")

由於posix.write寫管道是原子的,所以無須擔心多進程或多線程寫混亂的問題

不過這段代碼依賴luaposix庫,使用前需要安裝一下。

Lua 語言 15 分鐘快速入門 http://www.linuxidc.com/Linux/2013-06/86582.htm

Lua程序設計(第2版)中文 PDF http://www.linuxidc.com/Linux/2013-03/81833.htm

Lua程序設計(第二版)閱讀筆記 http://www.linuxidc.com/Linux/2013-03/81834.htm

NetBSD 將支持用 Lua 腳本開發內核組件 http://www.linuxidc.com/Linux/2013-02/79527.htm

CentOS 編譯安裝 Lua LuaSocket http://www.linuxidc.com/Linux/2011-08/41105.htm

Programming In Lua 高清PDF中文版 http://www.linuxidc.com/Linux/2015-05/117362.htm

如何配置一套優雅的Lua開發環境 http://www.linuxidc.com/Linux/2015-10/124397.htm

Lua 的詳細介紹:請點這裡
Lua 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved