簡體   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