如何使用日志记录模块避免重复输出 [英] How to avoid duplicate outputs using logging module

查看:69
本文介绍了如何使用日志记录模块避免重复输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用日志记录模块将脚本中以前的打印语句输出到控制台和日志文件.但是,每次我运行脚本时,输出似乎都将附加到控制台和日志中打印的内容,而不是覆盖那里的内容.例如,第一次运行脚本时,会在控制台和日志文件中获得以下输出:

I am using the logging module to output what used to be print statements in my script to both the console and a log file. However, each time I run the script, the output seems to append to what was printed in the console and the log, rather than overwrite what was there. For example, the first time I run the script I get this output in my console and log file:

This print statement is going to both the console and the log
The year is: 2015

第二次运行脚本时,我会在控制台中看到它:

The second time I run the script, I get this in the console:

This print statement is going to both the console and the log
This print statement is going to both the console and the log
The year is: 2015
The year is: 2015

第三次:

This print statement is going to both the console and the log
This print statement is going to both the console and the log
This print statement is going to both the console and the log
The year is: 2015
The year is: 2015
The year is: 2015

等.并且日志文件不断追加,所以我最终得到:

etc.. and the log file keeps appending so that I end up with:

This print statement is going to both the console and the log
The year is: 2015
This print statement is going to both the console and the log
This print statement is going to both the console and the log
The year is: 2015
The year is: 2015
This print statement is going to both the console and the log
This print statement is going to both the console and the log
This print statement is going to both the console and the log
The year is: 2015
The year is: 2015
The year is: 2015

无论重新运行脚本多少次,我都希望日志文件和控制台都只提供以下内容:

What I want is for both the log file and the console to only give me the following, no matter how many times I rerun the script:

This print statement is going to both the console and the log
The year is: 2015

注意:目前,我可以获得我想要的唯一方法是在脚本运行之间关闭Python,但这不是一个实际的解决方案.

Note: the only way I can currently get what I want is to shut down Python in between runs of the script, but that is not a practical solution.

我已经尝试过使用flush()并尝试执行以下操作:

I have experimented with using flush() and have tried doing something like this:

logger = logging.basicConfig(filemode='w', level=logging.DEBUG)

但是我无法使其与我的代码一起使用.有人可以帮忙吗?这是我的代码:

but I have not been able to get it to work with my code. Can someone please help? Here is my code:

import inspect
import logging
import datetime

def getDate():
    now = datetime.datetime.now()
    m = now.month
    d = now.day
    y = str(now.year)
    if m < 10:
        m = "0"+str(m)
    else:
        m = str(m)
    if d < 10:
        d = "0"+str(d)
    else:
        d = str(d)
    y = y[2:]
    formatted_date = m+d+y
    return formatted_date

def function_logger(file_level, console_level = None):
    function_name = inspect.stack()[1][3]
    logger = logging.getLogger(function_name)
    logger.setLevel(logging.DEBUG) #By default, logs all messages

    if console_level != None:
        ch = logging.StreamHandler() #StreamHandler logs to console
        ch.setLevel(console_level)
        ch_format = logging.Formatter('%(message)s')
        ch.setFormatter(ch_format)
        logger.addHandler(ch)

    log_name = 'Test_log' + getDate() + '.log'
    fh = logging.FileHandler(log_name.format(function_name))
    fh.setLevel(file_level)
    fh_format = logging.Formatter('%(message)s')
    fh.setFormatter(fh_format)
    logger.addHandler(fh)
    return logger

def f1():
    global logger
    year = '2015'
    logger.info("The year is: %s" % (year))

def main():

    global logger
    logger = function_logger(logging.INFO, logging.INFO)
    logger.info('This print statement is going to both the console and the log')
    f1()
    logging.shutdown()

if __name__ == '__main__':
    main()

推荐答案

感谢卢卡斯·格拉夫(Lucas Graf),以下是我固定代码以完全实现所需功能的方法:

Thanks to Lucas Graf, here is how I fixed the code to do exactly what I wanted:

def function_logger(file_level, console_level = None):
    function_name = inspect.stack()[1][3]
    logger = logging.getLogger(function_name)
    logger.setLevel(logging.DEBUG) #By default, logs all messages
    log_name = 'Test_log_' + getDate() + '.log'

    if not logger.handlers:
        if console_level != None:
            ch = logging.StreamHandler() #StreamHandler logs to console
            ch.setLevel(console_level)
            ch_format = logging.Formatter('%(message)s')
            ch.setFormatter(ch_format)
            logger.addHandler(ch)

        fh = logging.FileHandler(log_name.format(function_name), mode='w')
        fh.setLevel(file_level)
        fh_format = logging.Formatter('%(message)s')
        fh.setFormatter(fh_format)
        logger.addHandler(fh)

    return logger

关于此修复程序,需要注意三件事:

There are three things to note about this fix:

1:我在测试条件下移动了两个addHandlers:

1: I moved both addHandlers under the test condition:

if not logger.handlers:

2:我在Filhandler中添加了mode ='w':

2: I added mode='w' to the Filhandler:

fh = logging.FileHandler(log_name.format(function_name), mode='w')

3:我清除了main()底部的处理程序:

3: I cleared the handlers at the bottom of main():

logger.handlers = []

这篇关于如何使用日志记录模块避免重复输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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