Python logging - exc_info for file handler only

I define a root logger and handlers for it:

_root = logging.getLogger() _sh = logging.StreamHandler() _fh = logging.FileHandler('./error.log', delay = True) _root.addHandler(_sh) _root.addHandler(_fh) 

And an instance of the logger module:

 _log = logging.getLogger("Main") # In other file _log = logging.getLogger("Configuration") 

Now I _log.exception in try..except block:

 _log.exception("Test") 

Now I get the trace in the console and file. I am trying to disable exc_info printing using the console handler, but not with the file handler:

 class _TraceBackFilter(logging.Filter): def filter(self, rec): rec.exc_info = None return True _sh = logging.StreamHandler() _sh.addFilter(_TraceBackFilter()) _root.addHandler(_sh) 

This works with both the file handler and the console, traceback is completely removed for all handlers, but I only need it for the console. Is there a way to suppress exc_info only for the console handler and not for the file handler?

EDIT:

I am _TraceBackFilter class.

 class _TraceBackFilter(logging.Filter): def filter(self, rec): if rec.exc_info: logging.getLogger(rec.name).log(rec.levelno, rec.getMessage()) return False else: return True 

Now it works for the console handler, but in the file I have double messages, one with one and one without tracing.

+4
source share
2 answers

Create a subclass of logging.Formatter for your console handler that returns an empty string from its formatException method.

Exceptional text is cached in the record (in the exc_text attribute): if this is a false value (for example, an empty string), then formatException() will be formatException() to re-populate it, otherwise it will not. Thus, in your formatting class, you may need to override the format() method and set record.exc_text to a false value before calling the format() superclass method to ensure that you formatException() overridden formatException() . For example (not verified):

 class NoExceptionFormatter(logging.Formatter): def format(self, record): record.exc_text = '' # ensure formatException gets called return super(NoExceptionFormatter, self).format(record) def formatException(self, record): return '' 
+4
source

If the _sh handler is processed first with this filter, it looks like it can modify the actual trace object. Since the same trace object is passed to both _sh and _fh, _fh receives the already changed trace.

You can either create a new trace object in this filter, either without exc_info, or maybe just change the order so that addHandler is called first on _fh.

0
source

All Articles