我在Python中使用logging
模塊來編寫調試和錯誤消息。filehandler的不同日誌級別和Python中的顯示
我想寫入文件的所有消息logging.DEBUG
或更大。
但是,我只想打印到logging.WARNING
或更高的屏幕消息。
這可能只使用一個Logger
和一個FileHandler
?
我在Python中使用logging
模塊來編寫調試和錯誤消息。filehandler的不同日誌級別和Python中的顯示
我想寫入文件的所有消息logging.DEBUG
或更大。
但是,我只想打印到logging.WARNING
或更高的屏幕消息。
這可能只使用一個Logger
和一個FileHandler
?
正如前面提到的,處理程序非常容易創建和添加,因此使用兩個處理程序可能會更好。但是,如果出於某種原因想要堅持使用,Python logging cookbook有一個部分或多或少地描述了您想要執行的操作:記錄到控制檯和文件,但在不同級別(它甚至會告訴您如何執行不同的格式化)。它做它用單StreamHandler
,而不是一個FileHandler
,雖然:
import logging
# set up logging to file - see previous section for more details
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M',
filename='/temp/myapp.log',
filemode='w')
# define a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.INFO)
# set a format which is simpler for console use
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)
# Now, we can log to the root logger, or any other logger. First the root...
logging.info('Jackdaws love my big sphinx of quartz.')
# Now, define a couple of other loggers which might represent areas in your
# application:
logger1 = logging.getLogger('myapp.area1')
logger2 = logging.getLogger('myapp.area2')
logger1.debug('Quick zephyrs blow, vexing daft Jim.')
logger1.info('How quickly daft jumping zebras vex.')
logger2.warning('Jail zesty vixen who grabbed pay from quack.')
logger2.error('The five boxing wizards jump quickly.')
編輯:作爲該代碼仍然會產生兩個處理意見的討論,而是「隱藏」一個建設通過使用basicConfig的() 。我強烈建議你明確地創建兩者。
編號文件和屏幕輸出意味着您需要兩個處理程序。
使用一個處理程序,它正在寫入文件和屏幕。但在同一級別(logging.DEBUG)。 – cssndrx
@cssndrx:「一個處理程序,它正在寫入文件和屏幕。」我覺得很難理解。請**更新**問題以包括您正在使用的日誌記錄配置。 –
@eryksun:許多事情「可以完成」。我們需要看看他們實際**做了些什麼。 –
這仍然是兩個處理程序。只有你用'basicConfig(...)'「掩蓋」了'FileHandler'的創建,我寧願明確地創建它們。 – plundra
當然,你是對的。但是,我認爲這個(或類似的)是當他/她說只有一個記錄器輸出到兩個地方時,提問者想到的。在你的另一點上,我必須同意你的看法:明確聲明兩個處理程序更加清晰和簡潔。 – bdeniker