[英]How to log to file & stdout
我設置了以下日志記錄:
import logging
logging.basicConfig(level=logging.DEBUG,
format='[%(asctime)s] - %(funcName)s - %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='/tmp/affiliate.log',
filemode='w')
我將如何轉換以下兩個語句-寫入日志文件,然后輸出輸出:
logging.debug('>>>>> 401 Error: Cannot download file')
print '>>>>> 401 Error: Cannot download file'
合並成一個日志記錄,兩者兼而有之?
您不能basicConfig
做到這basicConfig
(至少不是在Python 2.7中; 3.3添加了新功能,尤其是handlers
參數),但是將記錄器設置為寫入兩個位置很容易。 日志記錄手冊詳細介紹了如何進行各種操作。
尚沒有完全解釋其中的一些菜譜條目,只是進行了演示,但您始終可以在logging
文檔中查找詳細信息。
您在這里尋找的關鍵是創建兩個處理程序— FileHandler('/tmp/affiliate.log')
和StreamHandler(sys.stdout)
。
如果要在日志文件和stdout
使用相同的格式,日志級別等,則本食譜的早期示例之一就是這樣做的,除了stderr
。 如果每種格式都需要不同的格式, 那么下一個示例將這樣做 。
因此,代替此:
logging.basicConfig(level=logging.DEBUG,
format='[%(asctime)s] - %(funcName)s - %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='/tmp/affiliate.log',
filemode='w')
做這個:
logger = logging.getLogger('')
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('/tmp/affiliate.log')
sh = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter('[%(asctime)s] - %(funcName)s - %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S')
fh.setFormatter(formatter)
sh.setFormatter(formatter)
logger.addHandler(fh)
logger.addHandler(sh)
請注意,我鏈接的第二個示例使用basicConfig
可以做的一切,然后在其上面添加第二個處理程序。 我認為這還不太清楚,但是如果您要這樣做,也可以做到。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.