Python logging: use milliseconds in time format Python logging: use milliseconds in time format python python

Python logging: use milliseconds in time format


This should work too:

logging.Formatter(fmt='%(asctime)s.%(msecs)03d',datefmt='%Y-%m-%d,%H:%M:%S')


Please note Craig McDaniel's solution is clearly better.


logging.Formatter's formatTime method looks like this:

def formatTime(self, record, datefmt=None):    ct = self.converter(record.created)    if datefmt:        s = time.strftime(datefmt, ct)    else:        t = time.strftime("%Y-%m-%d %H:%M:%S", ct)        s = "%s,%03d" % (t, record.msecs)    return s

Notice the comma in "%s,%03d". This can not be fixed by specifying a datefmt because ct is a time.struct_time and these objects do not record milliseconds.

If we change the definition of ct to make it a datetime object instead of a struct_time, then (at least with modern versions of Python) we can call ct.strftime and then we can use %f to format microseconds:

import loggingimport datetime as dtclass MyFormatter(logging.Formatter):    converter=dt.datetime.fromtimestamp    def formatTime(self, record, datefmt=None):        ct = self.converter(record.created)        if datefmt:            s = ct.strftime(datefmt)        else:            t = ct.strftime("%Y-%m-%d %H:%M:%S")            s = "%s,%03d" % (t, record.msecs)        return slogger = logging.getLogger(__name__)logger.setLevel(logging.DEBUG)console = logging.StreamHandler()logger.addHandler(console)formatter = MyFormatter(fmt='%(asctime)s %(message)s',datefmt='%Y-%m-%d,%H:%M:%S.%f')console.setFormatter(formatter)logger.debug('Jackdaws love my big sphinx of quartz.')# 2011-06-09,07:12:36.553554 Jackdaws love my big sphinx of quartz.

Or, to get milliseconds, change the comma to a decimal point, and omit the datefmt argument:

class MyFormatter(logging.Formatter):    converter=dt.datetime.fromtimestamp    def formatTime(self, record, datefmt=None):        ct = self.converter(record.created)        if datefmt:            s = ct.strftime(datefmt)        else:            t = ct.strftime("%Y-%m-%d %H:%M:%S")            s = "%s.%03d" % (t, record.msecs)        return s...formatter = MyFormatter(fmt='%(asctime)s %(message)s')...logger.debug('Jackdaws love my big sphinx of quartz.')# 2011-06-09 08:14:38.343 Jackdaws love my big sphinx of quartz.


Adding msecs was the better option, Thanks.Here is my amendment using this with Python 3.5.3 in Blender

import logginglogging.basicConfig(level=logging.DEBUG, format='%(asctime)s.%(msecs)03d %(levelname)s:\t%(message)s', datefmt='%Y-%m-%d %H:%M:%S')log = logging.getLogger(__name__)log.info("Logging Info")log.debug("Logging Debug")