'format':' %(asctime)s %(message)s ', } }, 'handlers': { 'console1 ': { 'class':'logging.StreamHandler ', 'formatter':'utc', }, 'console2 ': { 'class':'logging.StreamHandler ', 'formatter':'local', }, }, 'root': { 'handlers': ['console1 ','console2 '], } } if __name__ =='__main__ ': logging.config.dictConfig(LOGGING) logging.warning( 'The local time is %s ', time.asctime()) 

When this script is run, it should print something like: 

(continued from previous page) 

2015-10-17 12:53:29,501 The local time is Sat Oct 17 2015-10-17 13:53:29,501 The local time is Sat Oct 17 

showing how the time is formatted both as local time and UTC, one for each handler. 

## 27 Using a context manager for selective logging 

There are times when it would be useful to temporarily change the logging configuration and revert it back after doing something. For this, a context manager is the most obvious way of saving and restoring the logging context. Here is a simple example of such a context manager, which allows you to optionally change the logging level and add a logging handler purely in the scope of the context manager: 

import logging import sys classLoggingContext : def __init__ (self, logger, level = None , handler= None , close = True ): self.logger=logger self.level=level self.handler =handler self.close =close def __enter__ (self): if self.level is not None : self.old_level =self.logger.level self.logger.setLevel( self.level) if self.handler: self.logger.addHandler(self.handler) def __exit__ (self, et, ev, tb): if self.level is not None : self.logger.setLevel( self.old_level) if self.handler: self.logger.removeHandler( self.handler) if self.handler and self.close: 

(continues on next page) 

