1 basicConfig

参数说明

Format Description
filename Specifies that a FileHandler be created, using the specified filename, rather than a StreamHandler.
filemode If filename is specified, open the file in this mode. Defaults to 'a'.
format Use the specified format string for the handler.
datefmt Use the specified date/time format, as accepted by time.strftime().
level Set the root logger level to the specified level.
stream Use the specified stream to initialize the StreamHandler. Note that this argument is incompatible with filename - if both are present, stream is ignored.

示例

  1. import logging
  2. logging.basicConfig(
  3. format='[%(asctime)s %(funcName)s %(levelname)s] %(messsage)s',
  4. datefmt='%Y-%m-%d %H:%M:%S',
  5. level=logging.DEBUG)
  6. logger = logging.getLogger('TEST')
  7. logger.debug('start')
  8. logger.info('done')

可选的format

Attribute name Format Description
args You shouldn’t need to format this yourself. The tuple of arguments merged into msg to produce message, or a dict whose values are used for the merge (when there is only one argument, and it is a dictionary).
asctime %(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).
created %(created)f Time when the LogRecord was created (as returned by time.time()).
exc_info You shouldn’t need to format this yourself. Exception tuple (à la sys.exc_info) or, if no exception has occurred, None.
filename %(filename)s Filename portion of pathname.
funcName %(funcName)s Name of function containing the logging call.
levelname %(levelname)s Text logging level for the message ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL').
levelno %(levelno)s Numeric logging level for the message (DEBUG, INFO, WARNING, ERROR, CRITICAL).
lineno %(lineno)d Source line number where the logging call was issued (if available).
module %(module)s Module (name portion of filename).
msecs %(msecs)d Millisecond portion of the time when the LogRecord was created.
message %(message)s The logged message, computed as msg % args. This is set when Formatter.format() is invoked.
msg You shouldn’t need to format this yourself. The format string passed in the original logging call. Merged with args to produce message, or an arbitrary object (see Using arbitrary objects as messages).
name %(name)s Name of the logger used to log the call.
pathname %(pathname)s Full pathname of the source file where the logging call was issued (if available).
process %(process)d Process ID (if available).
processName %(processName)s Process name (if available).
relativeCreated %(relativeCreated)d Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded.
thread %(thread)d Thread ID (if available).
threadName %(threadName)s Thread name (if available).

logging的日志级别

Level Numeric value
CRITICAL 50
ERROR 40
WARNING 30
INFO 20
DEBUG 10
NOTSET 0

修改logger

  1. # ...
  2. logger.level = logging.INFO
  3. # or
  4. logger.level = 20
  5. # or
  6. logger.setLevel(logging.INFO)

2 addHandler

先创建logger,后添加handler

  1. # coding: utf8
  2. import sys
  3. import logging
  4. # 创建logger,设置level
  5. logger = logging.getLogger('TEST2')
  6. logger.setLevel(logging.DEBUG) # handler默认level
  7. # 创建formatter
  8. formatter = logging.Formatter(
  9. fmt='[%(asctime)s %(levelname)s:%(lineno)s] %(message)s',
  10. datefmt='%Y-%m-%d %H:%M:%S')
  11. # 创建stream handler
  12. hdlr1 = logging.StreamHandler(stream=sys.stderr) # 默认stderr
  13. hdlr1.setLevel(logging.INFO) # 重设level
  14. hdlr1.setFormatter(formatter) # 设置formatter
  15. # 创建file handler
  16. hdlr2 = logging.FileHandler('out.log', mode='w')
  17. hdlr2.setFormatter(formatter)
  18. # 为logger添加handler
  19. logger.addHandler(hdlr1)
  20. logger.addHandler(hdlr2) # 可添加多个handler
  21. logger.debug('debug message')
  22. logger.info('info message')
  23. logger.warn('warn message')

image.png

3 logging.config

通过配置文件的方式初始化logger