Python logging: use milliseconds in time format

后端 未结 10 1815
不知归路
不知归路 2020-12-02 05:36

By default logging.Formatter(\'%(asctime)s\') prints with the following format:

2011-06-09 10:54:40,638

where 638 is the milli

10条回答
  •  自闭症患者
    2020-12-02 05:46

    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 logging
    import datetime as dt
    
    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
    
    logger = 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.
    

提交回复
热议问题