除直接在程序中設置Logger、Handler、Formatter等外,還可將這些信息寫入配置文件。示例如下:
#logger.conf
###############Logger###############
[loggers]
keys=root,Logger2F,Logger2CF
[logger_root]
level=DEBUG
handlers=hWholeConsole
[logger_Logger2F]
handlers=hWholeFile
qualname=Logger2F
propagate=0
[logger_Logger2CF]
handlers=hPartialConsole,hPartialFile
qualname=Logger2CF
propagate=0
###############Handler###############
[handlers]
keys=hWholeConsole,hPartialConsole,hWholeFile,hPartialFile
[handler_hWholeConsole]
class=StreamHandler
level=DEBUG
formatter=simpFormatter
args=(sys.stdout,)
[handler_hPartialConsole]
class=StreamHandler
level=INFO
formatter=simpFormatter
args=(sys.stderr,)
[handler_hWholeFile]
class=FileHandler
level=DEBUG
formatter=timeFormatter
args=('out.txt', 'a')
[handler_hPartialFile]
class=FileHandler
level=WARNING
formatter=timeFormatter
args=('out.txt', 'w')
###############Formatter###############
[formatters]
keys=simpFormatter,timeFormatter
[formatter_simpFormatter]
format=[%(levelname)s] at %(filename)s,%(lineno)d: %(message)s
[formatter_timeFormatter]
format=%(asctime)s [%(levelname)s] at %(filename)s,%(lineno)d: %(message)s
datefmt=%Y-%m-%d(%a)%H:%M:%S
此處共創建三個Logger:root,將所有日志輸出至控制臺;Logger2F,將所有日志寫入文件;Logger2CF,將級別大于或等于INFO的日志輸出至控制臺,將級別大于或等于WARNING的日志寫入文件。
程序以如下方式解析配置文件和重定向輸出:
import logging, logging.config
logging.config.fileConfig("logger.conf")
logger = logging.getLogger("Logger2CF")
logger.debug('gubed'); logger.info('ofni'); logger.warn('nraw')
logger.error('rorre'); logger.critical('lacitirc')
logger1 = logging.getLogger("Logger2F")
logger1.debug('GUBED'); logger1.critical('LACITIRC')
logger2 = logging.getLogger()
logger2.debug('gUbEd'); logger2.critical('lAcItIrC')
運行后屏幕上顯示:
[INFO] at test.py,7: ofni
[WARNING] at test.py,7: nraw
[ERROR] at test.py,8: rorre
[CRITICAL] at test.py,8: lacitirc
[DEBUG] at test.py,14: gUbEd
[CRITICAL] at test.py,14: lAcItIrC
out.txt文件內容則為:
2016-05-13(Fri)20:31:21 [WARNING] at test.py,7: nraw
2016-05-13(Fri)20:31:21 [ERROR] at test.py,8: rorre
2016-05-13(Fri)20:31:21 [CRITICAL] at test.py,8: lacitirc
2016-05-13(Fri)20:31:21 [DEBUG] at test.py,11: GUBED
2016-05-13(Fri)20:31:21 [CRITICAL] at test.py,11: LACITIRC
三. 總結
以上就是關于Python標準輸出的重定向方式的全部內容,希望對學習python的朋友們能有所幫助,如果有疑問歡迎大家留言討論。
評論
查看更多