繁体   English   中英

如何在脚本末尾或调用时发送日志? 使用记录器模块

[英]how to send log at the end of script or when invoked? using logger module

有记录器模块和 SMTPHandler,当我注册它时,它会在每个日志上发送 email。

有没有办法告诉 SMTPHandler class “存储”日志,并且只在调用或脚本结束时发送

您可以编写一个自定义处理程序来保存日志记录,而不是直接发出它们:

import atexit
import logging


class SpoolingHandler(logging.Handler):

    def __init__(self, level, *, atexit_function) -> None:
        super().__init__(level)
        self.records = []
        if atexit_function:
            atexit.register(atexit_function, self.records)

    def handle(self, record) -> bool:
        self.records.append(record)
        return True


def send_email(records):
    print(f"Would now send an email with {len(records)} records:")
    for record in records:
        print(record)
    print("----")


def main():
    handler = SpoolingHandler(logging.INFO, atexit_function=send_email)
    logging.basicConfig(handlers=[handler], level=logging.INFO)
    logging.info("Hello")
    logging.warning("Oh no :(")


if __name__ == '__main__':
    main()

这打印出来

Would now send an email with 2 records:
<LogRecord: root, 20, so73483195.py, 28, "Hello">
<LogRecord: root, 30, so73483195.py, 29, "Oh no :(">
----

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM