如何将日志发送到 python 中的系统日志?

How do I send log to syslog in python?

我有一个脚本来处理一个文件。一开始我想检查文件是否存在,如果存在并且不为空或不太旧。如果满意继续处理。如果不满意,我如何登录到系统日志并退出而不继续? 这是我的代码:

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()

阅读了一些关于日志记录的文档,不太了解实现它的正确方法。我不确定我的逻辑是否有意义。我能给些建议吗?提前致谢。

您可以将 syslog 模块与 quit 函数一起使用:

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()