Home > Lua, Programming > Reading logs with a Named Pipe

Reading logs with a Named Pipe

November 22, 2012 Leave a comment Go to comments

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")
        print("Logs' pipe was created")

--- 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.")
        print("Logs' pipe has opened successfully.")

    return logfd

log_pipe = open_log_pipe()

for line in log_pipe:lines() do
        if string.find(line, LOG_STR) ~= nil then
            -- do something
    until true

Credits on this thread.

Categories: Lua, Programming Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s