there is the logger module and SMTPHandler which when i register it sends email on every log.
is there a way to tell the SMTPHandler class to "store" the logs and only send upon called or at the end of script
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 :(">
----
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.