Monday, 26 April 2021

Logging in python with correct timezone

I would like to write log in a file with the correct timezone time (Europe/Paris) in a UpdateSubsStatus.log file ...

Here what i tried, the commented line are what i tired but it does not work.

import pytz

class Formatter(logging.Formatter):
    """override logging.Formatter to use an aware datetime object"""
    def converter(self, timestamp):
        dt = datetime.datetime.fromtimestamp(timestamp)
        tzinfo = pytz.timezone('America/Denver')
        return tzinfo.localize(dt)
        
    def formatTime(self, record, datefmt=None):
        dt = self.converter(record.created)
        if datefmt:
            s = dt.strftime(datefmt)
        else:
            try:
                s = dt.isoformat(timespec='milliseconds')
            except TypeError:
                s = dt.isoformat()
        return s
#console = logging.StreamHandler()
logging.basicConfig(filename='UpdateSubsStatus.log', filemode='a', format='%(asctime)s;%(name)s - %(levelname)s - %(message)s',datefmt='%Y-%m-%d %H:%M:%S')
#console.setFormatter(Formatter)
#logging.getLogger('').addHandler(console)

Does it exist a simple way with the basic config to use a timezone ?

Regards



from Logging in python with correct timezone

No comments:

Post a Comment