用 nginx-lua 搭建的服務往往需要寫日誌。常見做法是採用 nginx 自帶的 access log 配合 logrotate 腳本,但這種方式無法滿足「一次請求寫多條日誌」的需求。
之前我用 C 和 Go 都實現過類似的功能,思路是:主進程寫管道,子進程讀管道,再交由 apache-rotatelogs 寫入日誌文件。這裡用 Lua 也照樣實現了一遍。
核心模塊代碼如下:
-- Rlog is a non-blocking logging module based on pipe.
-- Rotatelogs of Apache is recommended 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 receiver 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 感興趣,可以參考以下資源:
Lua 語言 15 分鐘快速入門 https://www.linuxidc.com/Linux/2013-06/86582.htm
Lua 程序設計(第2版)中文 PDF https://www.linuxidc.com/Linux/2013-03/81833.htm
Lua 程序設計(第二版)閱讀筆記 https://www.linuxidc.com/Linux/2013-03/81834.htm
NetBSD 將支持用 Lua 腳本開發內核組件 https://www.linuxidc.com/Linux/2013-02/79527.htm
CentOS 編譯安裝 Lua LuaSocket https://www.linuxidc.com/Linux/2011-08/41105.htm
Programming In Lua 高清 PDF 中文版 https://www.linuxidc.com/Linux/2015-05/117362.htm
如何配置一套優雅的 Lua 開發環境 https://www.linuxidc.com/Linux/2015-10/124397.htm
Lua 的詳細介紹:請點這裡
Lua 的下載地址:請點這裡