始终在Python日志记录文件的最后一行中包含特定文本吗?

时间:2019-03-21 18:54:59

标签: python logging

我正在学习日志记录,想知道如何在我的.py退出/退出/错误之前总是包含一些文本。

如果我运行脚本三次,则只有一个日志文件,其中存储了所有错误/信息/等。但我想在每个.py执行结束时添加如下内容:

--------- End of .PY Execution ---------

因此,在查看文件时,两次运行脚本后,我可以看到:

2019-03-21, ERROR                     [get_files.py:13] Timed out when trying to connect to 192.168.100.106
2019-03-21, ERROR                     [get_files.py:13] Timed out when trying to connect to 192.169.291.291
2019-03-21, ERROR                     [get_files.py:13] Timed out when trying to connect to 192.000.000.000
------------------ END OF .PY EXECUTION ------------------------------------------------------
2019-03-21, INFO               [get_files.py:20] Some text here as info
------------------ END OF .PY EXECUTION ------------------------------------------------------

这是脚本的模型(忽略是否实际上会按上述顺序返回这些错误,主要是我在某些地方使用了quit(),因此只需在logging.info("-------- END OF .PY EXECUTION -----------")调用后添加main()并非在所有情况下都有效)。

import logging

logging.basicConfig(filename=os.path.basename(__file__) + '.log',
                    level=logging.DEBUG,
                    format='%(asctime)s, %(levelname)s \
                    [%(filename)s:%(lineno)d] %(message)s',
                    datefmt='%Y-%m-%d')


def open_connection(ip):
    # Do things
    if someCondition:
        logging.error("Timed out when trying to connect to " + ip)
        quit()
    else:
        return something

def open_again():
    if someOtherCondition:
        logging.info("Some text here as info")


def main():
    lst = [some list of ip addresses]
    for ip in lst:
        test = open_connection(ip)
    open_again()


if __name__ == "__main__":
    main()

1 个答案:

答案 0 :(得分:1)

不要使用quit() 这不是一个好习惯,因为即使没有刷新日志框架,它也会退出该过程。

引发异常。 如果您不想在控制台上看到异常错误。抛出特定的错误消息,并使用try和except忽略它。