简体   繁体   English

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

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

there is the logger module and SMTPHandler which when i register it sends email on every log.有记录器模块和 SMTPHandler,当我注册它时,它会在每个日志上发送 email。

is there a way to tell the SMTPHandler class to "store" the logs and only send upon called or at the end of script有没有办法告诉 SMTPHandler class “存储”日志,并且只在调用或脚本结束时发送

You can write a custom handler that holds on to log records instead of emitting them directly:您可以编写一个自定义处理程序来保存日志记录,而不是直接发出它们:

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

This prints out这打印出来

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.

相关问题 无法使用记录器模块写入日志文件 - Not able to write into log file using logger module 在 Python 中使用记录器模块 - 无法同时记录控制台和文件 - Using logger module in Python - can't log both console and file 如何使用记录器以Python格式登录特定格式? - How to log in a specifc format in Python using logger? 在 Maya 2018 中使用记录器时,我的警告级别日志消息将 go 发送到脚本编辑器,但不是我的调试级别消息 - when using a logger in Maya 2018, my warning level log messages will go to the script editor, but not my debug level messages 为什么Flask logger在前面使用UWSGI时不登录docker? - Why Flask logger does not log in docker when using UWSGI in front? 在命令行上调用时找到uWSGI模块,但在使用Emperor调用时找不到 - uWSGI module found when invoked on the command line but not when invoked using emperor 从另一个脚本调用时如何使用 ArgumentParser 将参数传递给脚本 - How to pass argument to script with ArgumentParser when invoked from another script 如何将 pprint 模块的输出发送到日志文件 - how to send the output of pprint module to a log file 具有类和循环日志处理的Python Logger模块 - Python Logger module with a class and rotating log handling 全局更改记录器模块中的日志文件名 - Change log file name in logger module globally
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM