Home » Odeon Blogs » Stefan Talpalaru, CTO »

logging with UTC timestamps from python

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:

  1. import logging
  2. import time
  3. class UTCFormatter(logging.Formatter):
  4. converter = time.gmtime # not documented, had to read the module's source code ;-)
  5. logger = logging.getLogger('foobar')
  6. logger.setLevel(logging.DEBUG)
  7. fh = logging.FileHandler('some_log_file')
  8. fh.setLevel(logging.DEBUG)
  9. formatter = UTCFormatter('[%(asctime)s] %(message)s', '%d/%b/%Y:%H:%M:%S')
  10. fh.setFormatter(formatter)
  11. logger.addHandler(fh)


Category: Python

Discussion

  1. 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.


  2. You're right about the instance attribute.


  3. I've updated the Python documentation (py3k and release27-maint branches) to point out usage of the converter attribute.


  4. Tim Wilder on Feb 04, 2013 - 19:28 said:

    This post was very useful. Having my logs in UTC will be excellent.




Leave a Comment :

(required)


(required)




(required)








Page generated in: 0.22s