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
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')
2015-01-09T18:30:54+0100 something happened