Python logging module emits wrong timezone information

前端 未结 2 1425
孤城傲影
孤城傲影 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
    
    0 讨论(0)
  • 2021-01-12 02:25

    EDIT:

    You can set the time formatter by:

    logging.Formatter.converter = time.localtime
    

    to yield local time.

    Or:

    logging.Formatter.converter = time.gmtime
    

    to get UTC.

    As for local time + time zone, first of all, logging.Formatter uses time, which as you can see here does not really support TZ properly (look at the footnote).

    The cleanest alternative would be to write your own formatter that uses datetime, which apparently has quite the stupid way of using TZ. Basically to make your object "aware", I would go with pytz.

    0 讨论(0)
提交回复
热议问题