Search code examples
pythonsyslog

How do I send log to syslog in python?


I have a script to process a file. At the beginning I would like to check if the file exist, if exist and not empty or not too old. If satisfied continue processing. If not satisfied, how do I log to syslog and exit without continue? Here's my code:

import sys
import os
import time

if os.path.isfile("/path/file"):
    x=os.stat('/path/file')
    Result=(time.time()-x.st_mtime)
    if os.stat("/path/file").st_size != 0 && Result > 300:
        f = open("/path/file", "r")
    else:
        ## log to syslog then exit script
else:
    ## log to syslog thn exit script

## section to continue processing
f1_to_process = f.read()
...
f.close()

Read a few doc on logging, not quite understand the right way to implement it. I am not sure if my logic makes any sense. Could I have some advice? Thanks in advance.


Solution

  • You can use the syslog module along with the quit function:

    import sys
    import os
    import time
    from syslog import syslog
    
    def log_and_exit(message):
        syslog(message)
        quit()
    
    if os.path.isfile("/path/file"):
        x=os.stat('/path/file')
        Result=(time.time()-x.st_mtime)
        if os.stat("/path/file").st_size != 0 && Result > 300:
            f = open("/path/file", "r")
        else:
            log_and_exit("foo")
    else:
        log_and_exit("bar")
    
    ## section to continue processing
    f1_to_process = f.read()
    # ...
    f.close()