2012-07-20 101 views
-3

此代碼是否同時寫入日誌文件和控制檯?如何將日誌消息同時寫入日誌文件和控制檯?

logFile = open("logfile.log",a) 
print >>logFile,message 
logFile.close() 
+12

當你嘗試它時它做了什麼...... – avasal 2012-07-20 06:53:34

+1

它可能使用多個處理程序。一個用於處理文件('logging.FileHandler('mylog.log')'),另一個用於處理控制檯('logging.StreamHandler()')。請參閱https://docs.python.org/2/howto/logging-cookbook.html – 2014-07-27 06:20:15

回答

16

不,它不會寫入兩者。 print()只會寫入控制檯。關於您的原始代碼的一個簡短說明。我認爲你在某個地方定義了message,但代碼仍然不正確。因爲我相信你的意思是要附加到文件

open("logfile.log", "a") 

:您需要a各地報價在open聲明,像這樣。否則,由於a不是定義的變量,因此您的代碼會拋出NameError

然而,正如其他人所說,你應該強烈考慮使用logging模塊。以下是如何寫入控制檯和日誌文件的簡單示例。該代碼是部分地herehere得出:

import inspect 
import logging 

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('%(asctime)s - %(message)s') 
     ch.setFormatter(ch_format) 
     logger.addHandler(ch) 

    fh = logging.FileHandler("{0}.log".format(function_name)) 
    fh.setLevel(file_level) 
    fh_format = logging.Formatter('%(asctime)s - %(lineno)d - %(levelname)-8s - %(message)s') 
    fh.setFormatter(fh_format) 
    logger.addHandler(fh) 

    return logger 

def f1(): 
    f1_logger = function_logger(logging.DEBUG, logging.ERROR) 
    f1_logger.debug('debug message') 
    f1_logger.info('info message') 
    f1_logger.warn('warn message') 
    f1_logger.error('error message') 
    f1_logger.critical('critical message') 

def f2(): 
    f2_logger = function_logger(logging.WARNING) 
    f2_logger.debug('debug message') 
    f2_logger.info('info message') 
    f2_logger.warn('warn message') 
    f2_logger.error('error message') 
    f2_logger.critical('critical message') 

def main(): 
    f1() 
    f2() 
    logging.shutdown() 

main() 

由於記錄對象可以有多個處理程序,我們可以創建寫入不同的地方多個處理程序。在我的代碼中,function_logger函數爲它所調用的函數創建一個特定的記錄器對象。

功能f1()日誌DEBUG級消息和以上到文件f1.log,一邊寫ERROR級消息和以上到控制檯,用不同的格式爲每個。

但是,函數f2()不向控制檯記錄任何內容,只將WARNING級消息記錄到其日誌文件f2.log。分別

2012-07-20 10:46:38,950 - f1 - error message 
2012-07-20 10:46:38,953 - f1 - critical message 

這個輸出f1.logf2.log,:運行此腳本一次債收益率此輸出在控制檯上

f1.log

2012-07-20 10:46:38,950 - 26 - DEBUG - debug message 
2012-07-20 10:46:38,950 - 27 - INFO  - info message 
2012-07-20 10:46:38,950 - 28 - WARNING - warn message 
2012-07-20 10:46:38,950 - 29 - ERROR - error message 
2012-07-20 10:46:38,953 - 30 - CRITICAL - critical message 

f2.log

2012-07-20 10:46:38,960 - 36 - WARNING - warn message 
2012-07-20 10:46:38,960 - 37 - ERROR - error message 
2012-07-20 10:46:38,960 - 38 - CRITICAL - critical message 
+0

的第一個示例一個細節:從Py27開始,「logger.setLevel(logging.DEBUG)#默認情況下,記錄所有消息」是必不可少的。沒有它,setLevel()調用處理程序將不起作用:詳細信息級別將被鎖定在logging.warning上。 – kakyo 2013-09-08 01:56:12