Python牛刀小试(五)--logging模块
生活随笔
收集整理的這篇文章主要介紹了
Python牛刀小试(五)--logging模块
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
由于想給自己的Python程序添加日志功能,學(xué)習(xí)下Python的日志模塊。
一個(gè)簡單的例子:
import logging
##第一個(gè)簡單的例子
logging.warning('Watch out!') # will print a message to the console 輸出到控制臺
logging.info('I told you so') # will not print anything 沒有任何輸出信息 輸出至控制臺的信息,如下:
D:\stock>python test4_logger.py WARNING:root:Watch out! 輸出日志到文件中
##輸出到example日志文件中
logging.basicConfig(filename='example.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too') 在當(dāng)前目錄中,有一個(gè)example.log日志文件,輸出日志如下:
由于自己寫的模塊,需要模塊化,要有配置文件,能復(fù)用。控制臺和文件都能輸出。
源代碼如下:
配置文件如下:
[loggers] keys=root,simpleExample [handlers] keys=consoleHandler,fileHandler [formatters] keys=simpleFormatter [logger_root] level=DEBUG handlers=consoleHandler,fileHandler [logger_simpleExample] level=DEBUG handlers=consoleHandler,fileHandler qualname=simpleExample propagate=0 [handler_consoleHandler] class=StreamHandler level=DEBUG formatter=simpleFormatter args=(sys.stdout,) [formatter_simpleFormatter] format=%(asctime)s - %(name)s - %(levelname)s - %(message)s datefmt= [handler_fileHandler] class=logging.handlers.TimedRotatingFileHandler level=DEBUG formatter=simpleFormatter args=("zsd.log", "midnight")
Python執(zhí)行文件:
import logging
import logging.config
logging.config.fileConfig('logging.conf')
# create logger
logger = logging.getLogger('simpleExample')
# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')
一個(gè)簡單的例子:
點(diǎn)擊(此處)折疊或打開
點(diǎn)擊(此處)折疊或打開
點(diǎn)擊(此處)折疊或打開
import logging##輸出到example日志文件中
logging.basicConfig(filename='example.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too') 在當(dāng)前目錄中,有一個(gè)example.log日志文件,輸出日志如下:
點(diǎn)擊(此處)折疊或打開
DEBUG:root:This message should go to the log file INFO:root:So should this WARNING:root:And this, too ----------------------------------------簡單的日志的分割線-----------------------------------------------------------由于自己寫的模塊,需要模塊化,要有配置文件,能復(fù)用。控制臺和文件都能輸出。
源代碼如下:
配置文件如下:
點(diǎn)擊(此處)折疊或打開
Python執(zhí)行文件:
點(diǎn)擊(此處)折疊或打開
總結(jié)
以上是生活随笔為你收集整理的Python牛刀小试(五)--logging模块的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: String.charAT的运用
- 下一篇: 原创:为什么唐朝之后,西安很难再成为首都