Python记录器:不会覆盖原始日志吗? [英] Python logger: won't overwrite the original log?

查看:210
本文介绍了Python记录器:不会覆盖原始日志吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,当我将以下x次复制粘贴到python提示符时, 它将日志x次添加到指定文件的末尾.

So, when I copy paste the following x times to the python prompt, it add the log x times to the end of the designated file.

如何更改代码,以便每次复制时都将其粘贴到提示中, 我只是覆盖了现有文件(代码似乎不接受 mode = 'w'选项,或者我似乎不明白其含义)

How can I change the code so that each time I copy paste this to the prompt, I simply overwrite the existing file (the code seems to not accept the mode = 'w' option or I do not seem to understand its meaning)

def MinimalLogginf():
    import logging
    import os
    paths = {'work': ''}
    logger = logging.getLogger('oneDayFileLoader')
    LogHandler = logging.FileHandler(os.path.join(paths["work"] , "oneDayFileLoader.log"), mode='w')
    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    LogHandler.setFormatter(formatter)
    logger.addHandler(LogHandler) 
    logger.setLevel(logging.DEBUG)
    #Let's say this is an error:
    if(1 == 1):
        logger.error('overwrite')

所以我运行了一次: MinmalLoggingf()

So I run it once: MinmalLoggingf()

现在,我希望新的日志文件覆盖上一次运行时创建的日志文件:

Now, I want the new log file to overwrite the log file created on the previous run:

MinmalLoggingf()

推荐答案

如果我理解正确,那么您一次要运行几天的某个Python进程,并且希望每天轮换一次日志.我建议您使用自动旋转日志文件的处理程序,例如,使用另一种方法. http://www.blog. pythonlibrary.org/2014/02/11/python-how-to-create-rotating-logs/

If I understand correctly, you're running a certain Python process for days at a time, and want to rotate the log every day. I'd recommend you go a different route, using a handler that automatically rotates the log file, e.g. http://www.blog.pythonlibrary.org/2014/02/11/python-how-to-create-rotating-logs/

但是,如果您想以自己喜欢的相同方法使用过程来控制日志(Python控制台,粘贴代码.任务),嗯...

But, if you want to control the log using the process in the same method you're comfortable with (Python console, pasting in code.. extremely unpretty and error prone, but sometimes quick-n-dirty is sufficient for the task at hand), well...

您的问题是,每次粘贴代码时都会创建一个新的FileHandler,并将其添加到Logger对象.最后,您得到一个附加了X FileHandler的记录器,所有记录器都写入同一文件.试试这个:

Your issue is that you create a new FileHandler each time you paste in the code, and you add it to the Logger object. You end up with a logger that has X FileHandlers attached to it, all of them writing to the same file. Try this:

import logging
paths = {'work': ''}
logger = logging.getLogger('oneDayFileLoader')
if logger.handlers:
   logger.handlers[0].close()
   logger.handlers = []
logHandler = logging.FileHandler(os.path.join(paths["work"] , "oneDayFileLoader.log"), mode='w')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
logHandler.setFormatter(formatter)
logger.addHandler(logHandler) 
logger.setLevel(logging.DEBUG)
logger.error('overwrite')

根据您的请求,我还添加了一个使用TimedRotatingFileHandler的示例.请注意,我尚未在本地对其进行测试,因此,如果您遇到问题,请回信.

Based on your request, I've also added an example using TimedRotatingFileHandler. Note I haven't tested it locally, so if you have issues ping back.

import logging
from logging.handlers import TimedRotatingFileHandler

logPath = os.path.join('', "fileLoaderLog")
logger = logging.getLogger('oneDayFileLoader')
logHandler = TimedRotatingFileHandler(logPath,
                                   when="midnight",
                                   interval=1)
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
logHandler.setFormatter(formatter)
logger.addHandler(logHandler) 
logger.setLevel(logging.DEBUG)
logger.error('overwrite')

这篇关于Python记录器:不会覆盖原始日志吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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