Reputation: 114468
I get a regular non-root logger of the default type:
logger = logging.getLogger('a')
Now I want to change the type and get a new logger for the same name:
logging.setLoggerClass(type('NewLoggerClass', (logging.Logger,), {}))
logger = logging.getLogger('a')
I would like the second call to getLogger
to respect the new logger class I set. However, logger
remains the same instance of logging.Logger
instead of __main__.NewLoggerClass
.
How do I either remove an existing logger for a given name, or replace it with one of a different type?
Upvotes: 0
Views: 71
Reputation: 6808
If in doubt ... "Use the source, Luke!"
So spelunking into logging/__init__.py
, one can see that a call to logging.getLogger
actually invokes Logger.manager.getLogger
.
Logger.manager
is itself an instance of Manager
that was instatiated on module load.
Hunting in the Manager
class shows that it checks for existing logger objects in self.loggerDict
. This attribute acts as the 'cache' for instantiated logger class.
So if you want to replace a certain logger with a new logger class, you probably can do it by deleting it first. Maybe like this:
del logging.Logger.manager.loggerDict['a']
logging.setLoggerClass(type('NewLoggerClass', (logging.Logger,), {}))
logger = logging.getLogger('a')
Try it out!
Upvotes: 1
Reputation: 99465
You can't do this (other than low-level hackery) once a logger has been created. You'll need to call setLoggerClass()
before you instantiate any loggers via getLogger()
.
Upvotes: 1