简体   繁体   中英

Python: How to log debug+ messages only when an error occures, info+ otherwise

My objective:

  • If no error happened in the method, log only messages of level INFO and higher.
  • If an error message appears, log all messages of level DEBUG and higher prior to the error as well.

I found logging.handlers.MemoryHandler class: https://docs.python.org/2/library/logging.handlers.html#memoryhandler

It partly fits my purpose. It buffers all messages and flushes them whenever an error-level message appears. But if there is no error-message, it won't log anything at all.

I want my app to still log INFOs and WARNINGs if there were no error.

What's the best way to implement that?

The way I see it you can achieve something similar by configuring two loggers.

  1. INFO-Logger to log only INFO level logging
  2. DETAIL-Logger to log in DEBUG mode

As an example see the documentation

You can decide how to log them, same file (maybe) or separate files (my-simple.log and my-detailed.log)

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.

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