Python日志记录-每次应用程序运行时都会有新的日志文件 [英] Python logging - new log file every time application runs

查看:729
本文介绍了Python日志记录-每次应用程序运行时都会有新的日志文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在做研究,并且很难完成我希望达到的目标. 目前,这就是我所拥有的(testlog.py)

I've been doing research and am having an extremely difficult time completing what I'm hoping to achieve. Currently, this is what I have (testlog.py)

import logging
import logging.handlers

filename = "example.log"

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")

handler = logging.handlers.RotatingFileHandler(filename, mode = 'w', backupCount = 5)
handler.setLevel(logging.DEBUG)
handler.setFormatter(formatter)
logger.addHandler(handler)

ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
logger.addHandler(ch)

for i in range(10):
   logger.debug("testx") #where I alternate x from 1 thru 9 to see output

它当前成功打印到控制台和example.log,这是我想要的.

It currently successfully prints out to the console and to example.log, which is what I want.

每次运行它时,它都会创建一个新文件并替换旧的example.log,如下所示:

Every time I run it, it makes a new file and replaces the old example.log like so:

使用logger.debug("test1")

example.log包含应有的test1 10次

example.log contains test1 10 times like it should

logger.debug("test2")

它将example.log重写为包含test2 10次 等等...

it rewrites example.log to contain test2 10 times etc...

但是,我希望每次运行该程序时,该代码都能创建一个新的日志文件

However, I would like for the code to make a new log file every time I run the program so that I have

example.log

example.log

example.log1

example.log1

example.log2

example.log2

...

example.log5

example.log5

总而言之,我希望该文件将日志消息打印到控制台,日志文件中,并且每当我运行该程序时,我都希望有一个新的日志文件(最大* .5).谢谢!

In conclusion, I'd like for this file to print the log message to the console, to the log file, and I would like a new log file (up to *.5) whenever I run the program. Thanks!

推荐答案

logging.handlers.RotatingFileHandler 根据大小或日期轮换您的日志,但是您可以使用

logging.handlers.RotatingFileHandler rotates your logs based either on size or on date, but you can force it to rotate using RotatingFileHandler.doRollover() so something like:

import logging.handlers
import os

filename = "example.log"

# your logging setup

should_roll_over = os.path.isfile(filename)
handler = logging.handlers.RotatingFileHandler(filename, mode='w', backupCount=5)
if should_roll_over:  # log already exists, roll over!
    handler.doRollover()

# the rest of your setup...

应该像护身符一样工作.

Should work like a charm.

这篇关于Python日志记录-每次应用程序运行时都会有新的日志文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆