├── README.md └── lib └── resty └── logger.lua /README.md: -------------------------------------------------------------------------------- 1 | How to use? 2 | 3 | local logger = require("resty.logger"); 4 | 5 | logger.debug("i am debug"); --for debug 6 | 7 | logger.info("i am info"); --for info 8 | 9 | logger.error("i am error"); --for error 10 | 11 | -------------------------------------------------------------------------------- /lib/resty/logger.lua: -------------------------------------------------------------------------------- 1 | --module("resty.logger", package.seeall) 2 | 3 | local bit = require "bit" 4 | local ffi = require "ffi" 5 | local ffi_new = ffi.new 6 | local ffi_str = ffi.string 7 | local C = ffi.C; 8 | local bor = bit.bor; 9 | local ngx_today = ngx.today; 10 | local ngx_localtime = ngx.localtime 11 | local setmetatable = setmetatable 12 | local _error = error 13 | 14 | module(...) 15 | 16 | _VERSION = '0.01' 17 | 18 | local mt = { __index = _M } 19 | 20 | ffi.cdef[[ 21 | int write(int fd, const char *buf, int nbyte); 22 | int open(const char *path, int access, int mode); 23 | int close(int fd); 24 | ]] 25 | 26 | local O_RDWR = 0X0002; 27 | local O_CREAT = 0x0040; 28 | local O_APPEND = 0x0400; 29 | local S_IRWXU = 0x01C0; 30 | local S_IRGRP = 0x0020; 31 | local S_IROTH = 0x0004; 32 | 33 | -- log level 34 | local LVL_DEBUG = 1; 35 | local LVL_INFO = 2; 36 | local LVL_ERROR = 3; 37 | local LVL_NONE = 999; 38 | 39 | local today = ngx_today(); 40 | 41 | local logger_level = LVL_INFO; 42 | local logger_file = "/tmp/lomemo_custom.log."; 43 | local logger_fd = C.open(logger_file..today, bor(O_RDWR, O_CREAT, O_APPEND), bor(S_IRWXU, S_IRGRP, S_IROTH)); 44 | 45 | function shift_file() 46 | if ngx_today() ~= today then 47 | C.close(logger_fd); 48 | today = ngx_today(); 49 | logger_fd = C.open(logger_file..today, bor(O_RDWR, O_CREAT, O_APPEND), bor(S_IRWXU, S_IRGRP, S_IROTH)); 50 | end 51 | end 52 | 53 | function debug(msg) 54 | if logger_level > LVL_DEBUG then return end; 55 | shift_file(); 56 | 57 | local c = ngx_localtime() .. "|" .."D" .. "|" .. msg .. "\n"; 58 | C.write(logger_fd, c, #c); 59 | end 60 | 61 | function info(msg) 62 | if logger_level > LVL_INFO then return end; 63 | shift_file(); 64 | 65 | local c = ngx_localtime() .. "|" .."I" .. "|" .. msg .. "\n"; 66 | C.write(logger_fd, c, #c); 67 | end 68 | 69 | function error(msg) 70 | if logger_level > LVL_ERROR then return end; 71 | shift_file(); 72 | 73 | local c = ngx_localtime() .. "|" .."E" .. "|" .. msg .. "\n"; 74 | C.write(logger_fd, c, #c); 75 | end 76 | 77 | local class_mt = { 78 | -- to prevent use of casual module global variables 79 | __newindex = function (table, key, val) 80 | _error('attempt to write to undeclared variable "' .. key .. '"') 81 | end 82 | } 83 | 84 | setmetatable(_M, class_mt) 85 | --------------------------------------------------------------------------------