[英]How to use python logging to log to files?
我想使用python logging
工具將輸出logging
到不同的文件(每個模塊都有自己的日志文件)。 因此,我在每個python模塊的開頭添加了類似於以下內容的示例 :
... other imports ...
import logging
logger = logging.getLogger('factory')
fh = logging.FileHandler('log/factory.log')
fh.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s %(levelname)s: %(funcName)s:%(lineno)d %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
... code ...
然后使用logger.info("text")
記錄消息。 但是,盡管已創建數據,但沒有數據寫入到名為log/factory.log
的文件中! 目錄log
存在,並且我有權寫入該目錄。 將logging
功能與basicConfig
配合basicConfig
效果很好...
UPDATE
看起來好像沒有記錄日志,因為記錄logger
的日志記錄級別設置為logging.WARN
。 您還必須在記錄器上將級別顯式設置為logging.DEBUG
。 我認為未創建log/factory.log
文件,因為日志消息尚未達到該級別。 有關以下代碼的實時演示,請參見http://dbgr.cc/v :
import logging
import os
os.makedirs("log")
logger = logging.getLogger('factory')
fh = logging.FileHandler('log/factory.log')
fh.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s %(levelname)s: %(funcName)s:%(lineno)d %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
# notice that only the warning message is written
logger.debug("DEBUG MESSAGE")
logger.warn("WARNING MESSAGE")
logger.info("INFO MESSAGE")
with open("log/factory.log", "r") as f:
print f.read()
# now update the level on the Logger to logging.DEBUG:
logger.setLevel(logging.DEBUG)
logger.debug("DEBUG MESSAGE")
logger.warn("WARNING MESSAGE")
logger.info("INFO MESSAGE")
with open("log/factory.log", "r") as f:
print f.read()
在http://dbgr.cc/7上演示以下代碼:
import logging
import os
os.makedirs("log")
formatter = logging.Formatter('%(asctime)s %(levelname)s: %(funcName)s:%(lineno)d %(message)s')
# create logger with 'spam_application'
logger = logging.getLogger('factory')
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('log/factory.log')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
# just so we can see things as they happen in stdout/stderr
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(fh)
logger.addHandler(ch)
logger.debug("Debug log msg")
logger.info("Info log msg")
logger.warn("Warning log msg")
with open("log/factory.log", "r") as f:
print f.read()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.