logging with UTC timestamps from python
By default, the 'logging' module uses the local time for timestamps. Here's how you can make it use UTC with a custom formatter class:
- import logging
- import time
-
- class UTCFormatter(logging.Formatter):
- converter = time.gmtime # not documented, had to read the module's source code ;-)
-
- logger = logging.getLogger('foobar')
- logger.setLevel(logging.DEBUG)
- fh = logging.FileHandler('some_log_file')
- fh.setLevel(logging.DEBUG)
- formatter = UTCFormatter('[%(asctime)s] %(message)s', '%d/%b/%Y:%H:%M:%S')
- fh.setFormatter(formatter)
- logger.addHandler(fh)
Category: Python



Discussion
Whoops, I hadn't realised that the converter attribute was undocumented - I'll rectify this soon. However, you don't need to create a subclass: just instantiate a Formatter and set the converter on the instance to time.gmtime. Due to the way attribute lookup works, the instance attribute will be found if present, else the class attribute will be used.
You're right about the instance attribute.
I've updated the Python documentation (py3k and release27-maint branches) to point out usage of the converter attribute.
great!
Leave a Comment :
Leave a Comment