开发者

Python logging - exc_info only for file handler

I define 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 module logger instance:

_log = logging.getLogger("Main")
# In other file
_log = logging.getLogger(开发者_开发问答"Configuration")

Now i call _log.exception in try..except block:

_log.exception("Test")

Now i get traceback in console and file. I try to suppress printing of exc_info with console handler, but not with 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 on both file and console handler, traceback is completely removed for all handlers, but i need this only for console. Is any way to suppress exc_info only for console handler, not for file handler?

EDIT:

I modify _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 its works for console handler, but in file I have doubled messages, one with and one without traceback.


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

The exception text is cached in the record (in attribute exc_text): if this is a false value (e.g. empty string), then formatException() will be called to repopulate it, otherwise it won't be. So in your formatter class you may need to override the format() method and set record.exc_text to a false value before calling the superclass' format() method, to ensure your overridden formatException() gets called. For example (not tested):

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 ''


If the _sh handler is being processed first with that filter, it looks like it might be modifying the actual traceback object. Because the same traceback object is passed to both _sh and _fh, _fh receives the already-modified traceback.

You could either make a new traceback object in that filter, sans exc_info, or maybe just swap the order so addHandler is called on _fh first.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜