Python 日志输出,模块logging的使用
在实习之前,日志我基本上都是用输出printf,实习期间发现在做项目时,这种输出日志的方式已经不能满足需求了.
于是在网上查了下,发现python logging模块真的非常好用,在这里简单的记录下.
举个例子:
#coding:utf-8 import logging import logging.handlers log_file = 'test.log' handler = logging.handlers.RotatingFileHandler(log_file, maxBytes = 1024*1024, backupCount = 5) fmt = '%(asctime)s - %(filename)s:%(lineno)s - %(name)s - %(message)s' formatter = logging.Formatter(fmt) # 实例化formatter handler.setFormatter(formatter) # 为handler添加formatter logger = logging.getLogger('test') # 获取名为test的logger logger.addHandler(handler) # 为logger添加handler logger.setLevel(logging.INFO) # 设置存入文件的log等级 logger.info('first info message') #能够输出到指定的log文件 logger.debug('first debug message') #log等级小于指定的的等级,不能输出到指的log文件
执行代码后,查看test.log文件(这个文件会自动生成,之后会追加日志):
(crawler_env) [liangping@localhost ~]$ cat test.log
2017-09-28 17:44:04,188 - log_test.py:18 - test - first info message
至于formatter的配置,采用的是%(<dict key>)s的形式,就是字典的关键字替换 ,提供的关键字包括:
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. |