Reading logs with a Named Pipe
Recently I had to write a piece of code that constantly would read a log file and if something wrong had happened a specific action should be taken.
For this reason I wrote this piece of code in Lua using Named Pipes.
If you are not familiar with Named Pipes check them out (from Wikepedia: A named pipe is system-persistent and exists beyond the life of the process and must be deleted once it is no longer being used.).
LOG_FILE = "/path/to/the/log/file" LOG_PIPE = "/path/to/the/log_pipe" LOG_STR = "A word/phrase that we are searching for on the logs" --- Create the logs pipe function create_log_pipe() print("Creating the Logs' pipe...") local cmd_status = os.execute("rm -f " .. LOG_PIPE .. ";" .. "mkfifo " .. LOG_PIPE .. ";" .. "tail -n1 -f " .. LOG_FILE .." > " ..LOG_PIPE .. "&") if cmd_status == nil then print("[Error] Couldn't create the Logs' Pipe") exit else print("Logs' pipe was created") end end --- Open the logs' pipe -- @return the logs' pipe descriptor function open_log_pipe() print("Opening the Logs' pipe...") local logfd, _, _ = io.open(LOG_PIPE, "r") if not logfd then print("[Error] Couldn't open the Logs' pipe.") exit else print("Logs' pipe has opened successfully.") end return logfd end create_log_pipe() log_pipe = open_log_pipe() for line in log_pipe:lines() do repeat if string.find(line, LOG_STR) ~= nil then -- do something end until true end
Credits on this thread.