Python logging module emits wrong timezone information

前端 未结 2 1424
孤城傲影
孤城傲影 2021-01-12 01:47

I\'m running into an issue with Python 2.7 logging module. My system is Ubuntu 14.04 64bit, and I live in Italy (currently UTC+1, no daylight saving); the system is properly

2条回答
  •  情话喂你
    2021-01-12 02:20

    logging uses time module that doesn't store timezone in a time tuple and time.strftime() unlike datetime.strftime() doesn't support %z on Python 2. You could override Formatter.formatTime() method to use timezone-aware datetime objects as @dmg suggested instead:

    #!/usr/bin/env python
    import logging
    from datetime import datetime
    
    import tzlocal # $ pip install tzlocal
    
    def posix2local(timestamp, tz=tzlocal.get_localzone()):
        """Seconds since the epoch -> local time as an aware datetime object."""
        return datetime.fromtimestamp(timestamp, tz)
    
    class Formatter(logging.Formatter):
        def converter(self, timestamp):
            return posix2local(timestamp)
    
        def formatTime(self, record, datefmt=None):
            dt = self.converter(record.created)
            if datefmt:
                s = dt.strftime(datefmt)
            else:
                t = dt.strftime(self.default_time_format)
                s = self.default_msec_format % (t, record.msecs)
            return s
    
    logger = logging.getLogger(__name__)
    handler = logging.StreamHandler()
    handler.setFormatter(Formatter("%(asctime)s %(message)s", "%Y-%m-%dT%H:%M:%S%z"))
    logger.addHandler(handler)
    logger.setLevel(logging.DEBUG)
    
    logger.info('something happened')
    

    Output

    2015-01-09T18:30:54+0100 something happened
    

提交回复
热议问题