一个简单的例子:
点击(此处)折叠或打开
-
import logging
-
-
##第一个简单的例子
-
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!
点击(此处)折叠或打开
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')
##输出到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')
点击(此处)折叠或打开
DEBUG:root:This message should go to the log file
INFO:root:So should this
WARNING:root:And this, too
由于自己写的模块,需要模块化,要有配置文件,能复用。控制台和文件都能输出。
源代码如下:
配置文件如下:
点击(此处)折叠或打开
- [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执行文件:
点击(此处)折叠或打开
-
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')