Jon*_*han 141 python time logging
默认情况下logging.Formatter('%(asctime)s'),使用以下格式打印:
2011-06-09 10:54:40,638
Run Code Online (Sandbox Code Playgroud)
其中638是毫秒.我需要将逗号更改为点:
2011-06-09 10:54:40.638
Run Code Online (Sandbox Code Playgroud)
格式化我可以使用的时间:
logging.Formatter(fmt='%(asctime)s',datestr=date_format_str)
Run Code Online (Sandbox Code Playgroud)
但是文档没有指定如何格式化毫秒.我发现这个SO问题谈论微秒,但是a)我更喜欢毫秒和b)以下不适用于Python 2.6(我正在研究),因为%f:
logging.Formatter(fmt='%(asctime)s',datefmt='%Y-%m-%d,%H:%M:%S.%f')
Run Code Online (Sandbox Code Playgroud)
    Cra*_*iel 290
这也应该有效:
logging.Formatter(fmt='%(asctime)s.%(msecs)03d',datefmt='%Y-%m-%d,%H:%M:%S')
Run Code Online (Sandbox Code Playgroud)
        unu*_*tbu 66
请注意Craig McDaniel的解决方案显然更好.
logging.Formatter的formatTime方法如下所示:
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
Run Code Online (Sandbox Code Playgroud)
请注意逗号"%s,%03d".这不能通过指定datefmt因为ct是a 来修复,time.struct_time并且这些对象不记录毫秒.
如果我们改变定义ct使它成为一个datetime对象而不是一个struct_time,那么(至少在现代版本的Python中)我们可以调用ct.strftime,然后我们可以%f用来格式化微秒:
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.
Run Code Online (Sandbox Code Playgroud)
或者,要获得毫秒,请将逗号更改为小数点,并省略datefmt参数:
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.
Run Code Online (Sandbox Code Playgroud)
        Mas*_*mes 16
添加msecs是更好的选择,谢谢.以下是我在Blender中使用Python 3.5.3的修正案
import logging
logging.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")
Run Code Online (Sandbox Code Playgroud)
        小智 12
我发现最简单的方法是覆盖default_msec_format:
formatter = logging.Formatter('%(asctime)s')
formatter.default_msec_format = '%s.%03d'
Run Code Online (Sandbox Code Playgroud)
        这里有许多过时、过于复杂和奇怪的答案。原因是文档不够,简单的解决办法就是直接使用basicConfig()和设置如下:
logging.basicConfig(datefmt='%Y-%m-%d %H:%M:%S', format='{asctime}.{msecs:0<3.0f} {name} {threadName} {levelname}: {message}', style='{')
Run Code Online (Sandbox Code Playgroud)
这里的技巧是您还必须设置datefmt参数,因为默认设置会将其弄乱,而不是(当前)在操作方法 python 文档中显示的内容。所以宁可看看这里。
另一种可能更简洁的方法是使用以下方法覆盖default_msec_format变量:
formatter = logging.Formatter('%(asctime)s')
formatter.default_msec_format = '%s.%03d'
Run Code Online (Sandbox Code Playgroud)
但是,由于未知原因,这不起作用。
附注。我正在使用 Python 3.8。
小智 5
一个不需要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
Run Code Online (Sandbox Code Playgroud)
通过这种方式,可以根据需要编写日期格式,甚至可以通过使用%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
Run Code Online (Sandbox Code Playgroud)
        我想出了一个两行代码来让 Python 日志模块以 RFC 3339(符合 ISO 1801 标准)格式输出时间戳,同时具有格式正确的毫秒和时区,并且没有外部依赖:
import datetime
import logging
# Output timestamp, as the default format string does not include it
logging.basicConfig(format="%(asctime)s: level=%(levelname)s module=%(module)s msg=%(message)s")
# Produce RFC 3339 timestamps
logging.Formatter.formatTime = (lambda self, record, datefmt: datetime.datetime.fromtimestamp(record.created, datetime.timezone.utc).astimezone().isoformat())
Run Code Online (Sandbox Code Playgroud)
例子:
>>> logging.getLogger().error("Hello, world!")
2021-06-03T13:20:49.417084+02:00: level=ERROR module=<stdin> msg=Hello, world!
Run Code Online (Sandbox Code Playgroud)
或者,最后一行可以写成如下:
def formatTime_RFC3339(self, record, datefmt=None):
    return (
        datetime.datetime.fromtimestamp(record.created, datetime.timezone.utc)
        .astimezone()
        .isoformat()
    )
logging.Formatter.formatTime = formatTime_RFC3339
Run Code Online (Sandbox Code Playgroud)
该方法也可以用于特定的格式化程序实例,而不是在类级别覆盖,在这种情况下,您需要self从方法签名中删除。
|   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           80750 次  |  
        
|   最近记录:  |