在Python中,上面以实现的和已经实现的,都可以使用logging模块迅速搞定,且仅仅只须要一个配置文件,两行代码,实现过程以下(仅以输出的磁盘文件为例,命令输出只须要修改配置文件便可,具体可查API手册): python
1. 定义配置文件logging.conf: app
[loggers] keys=root,applog [handlers] keys=rotateFileHandler [formatters] keys=applog_format [formatter_applog_format] format=[%(asctime)s - %(name)s]%(levelname)s: %(message)s - %(filename)s:%(lineno)d [logger_root] level=NOTSET handlers=rotateFileHandler [logger_applog] level=NOTSET handlers=rotateFileHandler qualname=simple_example [handler_rotateFileHandler] class=handlers.RotatingFileHandler level=NOTSET formatter=applog_format args=('log_1.log', 'a', 10000, 9)
注意前三个[ ]中的keys,这个在后面各[ ]中定义定义,section的取名格式如looger_自定义名称, handler_自定义名称,我偷懒直接使用了标准名称,其余同样,最后一个要注意的就是format,即日志文件中内容的格式,具体见后面附一。level参数是日志级别,可扩展,若是使用python本身的,有如下四个级别: 测试
Level Numeric value
CRITICAL 50
ERROR 40
WARNING 30
INFO 20
DEBUG 10
NOTSET 0
this
例如配置文件中level定义为WARN,则INFO, DEBUG,NOTSET三个级别的日志点则不会输出,很方便的作到了日志级别控制。args定义了日志方件名,写方式,最大大小,保存最多个数等属性。 spa
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging import logging.config #日志初始化 LOG_FILENAME = 'logging.conf' logging.config.fileConfig(LOG_FILENAME) logger = logging.getLogger("simple_log_example") #测试代码 logger.debug("debug message") logger.info("info message") logger.warn("warn message") logger.error("error message") logger.critical("critical message")运行后,查看日志文件,内容以下:
Format Description %(name)s Name of the logger (logging channel). %(levelno)s Numeric logging level for the message (DEBUG, INFO, WARNING, ERROR, CRITICAL). %(levelname)s Text logging level for the message ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'). %(pathname)s Full pathname of the source file where the logging call was issued (if available). %(filename)s Filename portion of pathname. %(module)s Module (name portion of filename). %(funcName)s Name of function containing the logging call. %(lineno)d Source line number where the logging call was issued (if available). %(created)f Time when the LogRecord was created (as returned by time.time()). %(relativeCreated)d Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded. %(asctime)s Human-readable time when the LogRecord was created. By default this is of the form “2003-07-08 16:49:45,896” (the numbers after the comma are millisecond portion of the time). %(msecs)d Millisecond portion of the time when the LogRecord was created. %(thread)d Thread ID (if available). %(threadName)s Thread name (if available). %(process)d Process ID (if available). %(message)s The logged message, computed as msg % args.