2015-02-05 68 views
1

我正在使用日誌記錄模塊將腳本中用於打印語句的內容輸出到控制檯和日誌文件。但是,每次運行腳本時,輸出都會附加到控制檯和日誌中打印的內容上,而不是覆蓋那裏的內容。例如,我第一次運行該腳本我在控制檯中看到這個輸出和日誌文件:如何使用日誌記錄模塊避免重複輸出

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 

等和日誌文件將追加讓我結束了:

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 

我要的是兩者的日誌文件和控制檯只給我下面的,無論多少次,我重新運行該腳本:

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

注:只有這樣,我目前能得到什麼,我想要在腳本運行之間關閉Python,但這不是一個實際的解決方案。

我已經嘗試使用沖水(),並嘗試做這樣的事情:

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

,但我一直沒能得到它與我的代碼工作。有人可以幫忙嗎?這裏是我的代碼:

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() 
+1

你看到這一點,因爲所有的處理程序會發出一個記錄一次,如果你運行你的腳本多次,您將在每次調用addHandler()時調用一個新的處理程序。要麼跟蹤你的日誌處理程序,並在'try..finally'中再次刪除它們,要麼在添加它們之前檢查是否已經註冊了你要添加的類型。 – 2015-02-05 18:28:49

+0

(在每次運行期間打印'logger.handlers'以查看發生了什麼) – 2015-02-05 18:33:08

+0

謝謝。如果不是logger.handlers,請將兩個addHandler放在下面: 解決了重複條目的問題。但是,只有日誌文件存在第二個問題,即日誌仍被附加到而不是被覆蓋。我該如何解決這個剩餘的日誌問題? – 2015-02-05 19:22:13

回答

1

感謝盧卡斯·格拉夫,這裏是我固定的代碼做正是我想要的:

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 

有三件事情需要注意有關此修復程序:

1:我移動測試條件下都addHandlers:

if not logger.handlers: 

2:我添加模式= 'W' 到Filhandler:

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

3:我清除了處理器在主要底部():

logger.handlers = [] 
相關問題