正确的记录日志

看过本章第一节的同学应该还记得,log_by_lua* 是一个请求经历的最后阶段。由于记日志跟应答内容无关,Nginx 通常在结束请求之后才更新访问日志。由此可见,如果我们有日志输出的情况,最好统一到 log_by_lua* 阶段。如果我们把记日志的操作放在 content_by_lua* 阶段,那么将线性的增加请求处理时间。

在公司某个定制化项目中,Nginx 上的日志内容都要输送到 syslog 日志服务器。我们使用了lua-resty-logger-socket这个库。

调用示例代码如下(有问题的):

  1. -- lua_package_path "/path/to/lua-resty-logger-socket/lib/?.lua;;";
  2. --
  3. -- server {
  4. -- location / {
  5. -- content_by_lua_file lua/log.lua;
  6. -- }
  7. -- }
  8. -- lua/log.lua
  9. local logger = require "resty.logger.socket"
  10. if not logger.initted() then
  11. local ok, err = logger.init{
  12. host = 'xxx',
  13. port = 1234,
  14. flush_limit = 1, --日志长度大于flush_limit的时候会将msg信息推送一次
  15. drop_limit = 99999,
  16. }
  17. if not ok then
  18. ngx.log(ngx.ERR, "failed to initialize the logger: ",err)
  19. return
  20. end
  21. end
  22. local msg = string.format(.....)
  23. local bytes, err = logger.log(msg)
  24. if err then
  25. ngx.log(ngx.ERR, "failed to log message: ", err)
  26. return
  27. end

在实测过程中我们发现了些问题:

  • 缓存无效:如果 flush_limit 的值稍大一些(例如 2000),会导致某些体积比较小的日志出现莫名其妙的丢失,所以我们只能把 flush_limit 调整的很小
  • 自己拼写 msg 所有内容,比较辛苦

那么我们来看lua-resty-logger-socket这个库的 log 函数是如何实现的呢,代码如下:

  1. function _M.log(msg)
  2. ...
  3. if (debug) then
  4. ngx.update_time()
  5. ngx_log(DEBUG, ngx.now(), ":log message length: " .. #msg)
  6. end
  7. local msg_len = #msg
  8. if (is_exiting()) then
  9. exiting = true
  10. _write_buffer(msg)
  11. _flush_buffer()
  12. if (debug) then
  13. ngx_log(DEBUG, "Nginx worker is exiting")
  14. end
  15. bytes = 0
  16. elseif (msg_len + buffer_size < flush_limit) then -- 历史日志大小+本地日志大小小于推送上限
  17. _write_buffer(msg)
  18. bytes = msg_len
  19. elseif (msg_len + buffer_size <= drop_limit) then
  20. _write_buffer(msg)
  21. _flush_buffer()
  22. bytes = msg_len
  23. else
  24. _flush_buffer()
  25. if (debug) then
  26. ngx_log(DEBUG, "logger buffer is full, this log message will be "
  27. .. "dropped")
  28. end
  29. bytes = 0
  30. --- this log message doesn't fit in buffer, drop it
  31. ...

由于在 content_by_lua* 阶段变量的生命周期会随着请求的终结而终结,所以当日志量小于 flush_limit 的情况下这些日志就不能被累积,也不会触发 _flush_buffer 函数,所以小日志会丢失。

这些坑回头看来这么明显,所有的问题都是因为我们把 lua/log.lua 用错阶段了,应该放到 log_by_lua* 阶段,所有的问题都不复存在。

修正后:

  1. lua_package_path "/path/to/lua-resty-logger-socket/lib/?.lua;;";
  2. server {
  3. location / {
  4. content_by_lua_file lua/content.lua;
  5. log_by_lua_file lua/log.lua;
  6. }
  7. }

这里有个新问题,如果我的 log 里面需要输出一些 content 的临时变量,两阶段之间如何传递参数呢?

方法肯定有,推荐下面这个:

  1. location /test {
  2. rewrite_by_lua_block {
  3. ngx.say("foo = ", ngx.ctx.foo)
  4. ngx.ctx.foo = 76
  5. }
  6. access_by_lua_block {
  7. ngx.ctx.foo = ngx.ctx.foo + 3
  8. }
  9. content_by_lua_block {
  10. ngx.say(ngx.ctx.foo)
  11. }
  12. }

更多有关 ngx.ctx 信息,请看这里