gpt4 book ai didi

python - 日志轮换 - python 和 windows

转载 作者:可可西里 更新时间:2023-11-01 13:48:42 24 4
gpt4 key购买 nike

(我已经搜索过,但没有找到这个问题的重复项,但很高兴得到其他证明)。

我需要从一些 Python 代码中轮换日志。代码在 Windows (Server 2008 R2) 上运行。

最初我使用了 TimedRotatingFileHandler(来自 Python 的 logging.handlers 包),但这并不能满足我们的需要,因为据我所知,这是一个多处理问题(subprocess.check_call 是用于启动另一个应用程序)。

我已经检查了 ConcurrentLogHandler,它看起来可以胜任这项工作,但我有点担心它自 2013 年以来就没有更新过(尽管最近提出了问题)。

更新:open bug (自 2013 年起)表示 ConcurrentLogHandler 不适用于 Python 2.7/Windows。在记录日志时,代码只是挂起。

是否有我应该使用的最佳实践 Windows 解决方案?

最佳答案

也许我遗漏了什么,但是 Python 的日志记录模块带有一个 RotatingFileHandler:

import logging
import time

from logging.handlers import RotatingFileHandler

#----------------------------------------------------------------------
def create_rotating_log(path):
"""
Creates a rotating log
"""
logger = logging.getLogger("Rotating Log")
logger.setLevel(logging.INFO)

# add a rotating handler
handler = RotatingFileHandler(path, maxBytes=20,
backupCount=5)
logger.addHandler(handler)

for i in range(10):
logger.info("This is test log line %s" % i)
time.sleep(1.5)

#----------------------------------------------------------------------
if __name__ == "__main__":
log_file = r"c:\path\to\test.log"
create_rotating_log(log_file)

这对我来说在 Windows 7 上使用 Python 2.7 时效果很好。这里有几个更详细的链接:

关于python - 日志轮换 - python 和 windows,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37402702/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com