Galmi
Galmi

Reputation: 763

Python Logging - Apply formatter globally

I use phrase !Silent to determine where the log record will be saved.
If log record message contains !Silent at the beginning of string, my Filter subclass rejects this message in a StreamHandler. But message is passed to other handlers such as FileHandler or MemoryHandler, and is passed with !Silent phrase.

I created simple Formatter subclass to strip this phrase, including white characters on beginning of string, but I have trouble with applying this formatter to handlers.

In many places of my application i modify root logger handlers, creating, adding and removing it. Each of these handlers should have my Formatter subclass, but adding manually to each of it is little uncomfortable.

I looking for way to apply Formatter class globally to root logger, or overwrite root logger addHandler method to add filter to handler before adding it to root logger. Or simpler way if exist.

Upvotes: 2

Views: 278

Answers (1)

mac
mac

Reputation: 43091

Honestly, I am not sure I fully understood your question, so forgive me if my answer is not what you are lookng for... yet, instead applying a filter on the input of every handler, I would add a property to the unicode (or string) object that you are passing around. Something like:

>>> class LogMsg(unicode):
...      def __new__(cls, string_):
...         if string_[:7] == '!Silent':
...             cls.nolog = True
...             return super(LogMsg, cls).__new__(cls, string_[7:])
...         else:
...             cls.nolog = False
...             return super(LogMsg, cls).__new__(cls, string_)
... 
>>> a = LogMsg('The hard drive is on fire!')
>>> a
u'The hard drive is on fire!'
>>> a.nolog
False
>>> b = LogMsg('!SilentMy feet stink! :(')
>>> b
u'My feet stink! :('
>>> b.nolog
True

This way you could simply pass around 'string' that never display !Silent but has an hidden flag (nolog) that you can test only in case you need to.

HTH, /mac

Upvotes: 1

Related Questions