默认情况下logging.Formatter('%(asctime)s')打印如下格式:

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

638是毫秒。我需要把逗号换成一个点:

2011-06-09 10:54:40.638

格式化我可以使用的时间:

logging.Formatter(fmt='%(asctime)s',datestr=date_format_str)

但是,文档没有指定如何格式化毫秒。我发现了这个SO问题,它谈论的是微秒,但是a)我更喜欢毫秒,b)由于%f,下面的问题在Python 2.6(我正在工作)上不起作用:

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

当前回答

到目前为止,下面的代码与python3完全兼容。

         logging.basicConfig(level=logging.DEBUG,
                     format='%(asctime)s %(levelname)-8s %(message)s',
                     datefmt='%Y/%m/%d %H:%M:%S.%03d',
                     filename=self.log_filepath,
                     filemode='w')

给出以下输出

2020/01/11 18:51:19.011信息

其他回答

如果你用箭头或者不介意用箭头的话。你可以用python的时间格式代替arrow的时间格式。

import logging

from arrow.arrow import Arrow


class ArrowTimeFormatter(logging.Formatter):

    def formatTime(self, record, datefmt=None):
        arrow_time = Arrow.fromtimestamp(record.created)

        if datefmt:
            arrow_time = arrow_time.format(datefmt)

        return str(arrow_time)


logger = logging.getLogger(__name__)

default_handler = logging.StreamHandler()
default_handler.setFormatter(ArrowTimeFormatter(
    fmt='%(asctime)s',
    datefmt='YYYY-MM-DD HH:mm:ss.SSS'
))

logger.setLevel(logging.DEBUG)
logger.addHandler(default_handler)

现在你可以在datefmt属性中使用箭头的所有时间格式。

一个简单的扩展不需要datetime模块,也不像其他解决方案那样受到限制,它使用简单的字符串替换,如下所示:

import logging
import time

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

通过使用%F表示毫秒,可以任意编写日期格式,甚至允许区域差异。例如:

log = logging.getLogger(__name__)
log.setLevel(logging.INFO)

sh = logging.StreamHandler()
log.addHandler(sh)

fm = MyFormatter(fmt='%(asctime)s-%(levelname)s-%(message)s',datefmt='%H:%M:%S.%F')
sh.setFormatter(fm)

log.info("Foo, Bar, Baz")
# 03:26:33.757-INFO-Foo, Bar, Baz

这里有许多过时的、过于复杂和奇怪的答案。原因是文档是不充分的,简单的解决方案是使用basicConfig(),并设置如下:

logging.basicConfig(datefmt='%Y-%m-%d %H:%M:%S', format='{asctime}.{msecs:0<3.0f} {name} {threadName} {levelname}: {message}', style='{')

这里的技巧是,你还必须设置datefmt参数,因为默认的参数会把它弄乱,并且不是(目前)在python指南文档中显示的内容。所以还是看这里吧。


另一种可能更干净的方法是覆盖default_msec_format变量:

formatter = logging.Formatter('%(asctime)s')
formatter.default_msec_format = '%s.%03d'

然而,由于未知的原因,这并没有起作用。

PS.我使用的是Python 3.8。

使用这个智能答案的时区和选择的答案,你可以用你想要的格式构建毫秒和时区:

import logging
import time

if __name__ == "__main__":
    tz = time.strftime('%z')
    logging.basicConfig(
        format=(
            "%(asctime)s.%(msecs)03d" + tz + " %(levelname)s "
            "%(pathname)s:%(lineno)d[%(threadName)s]: %(message)s"
        ),
        level=logging.DEBUG,
        datefmt="%Y-%m-%dT%H:%M:%S",
    )
    logging.info("log example")

就我个人而言,我喜欢以UTC格式保存所有日志,但在日志中显式地将其作为没有时区的datetime,这在多区域应用程序中是没有意义的:

    logging.Formatter.converter = time.gmtime
    logging.basicConfig(
        format=(
            "%(asctime)s.%(msecs)03d+0000 %(levelname)s "
            "%(pathname)s:%(lineno)d[%(threadName)s]: %(message)s"
        ),
        level=logging.DEBUG,
        datefmt="%Y-%m-%dT%H:%M:%S",
    )

到目前为止,下面的代码与python3完全兼容。

         logging.basicConfig(level=logging.DEBUG,
                     format='%(asctime)s %(levelname)-8s %(message)s',
                     datefmt='%Y/%m/%d %H:%M:%S.%03d',
                     filename=self.log_filepath,
                     filemode='w')

给出以下输出

2020/01/11 18:51:19.011信息