日志级别对应值如下表所示。了解这些有助于你定义自己的日志级别的相对关系。如果你定义的级别与已有的数值相同,则原有的级别会被覆盖。
级别 | 数值 |
CRITICAL | 50 |
ERROR | 40 |
WARNING | 30 |
INFO | 20 |
DEBUG | 10 |
NOTSET | 0 |
生成log的几个方法, 这几个方法安重要程度依次排开, logger的设置可以影响一部分呢不重要的内容记录到日志当中。
debug(log_message, [*args[, **kwargs]])
info(log_message, [*args[, **kwargs]])
warning(log_message, [*args[, **kwargs]])
error(log_message, [*args[, **kwargs]])
critical(log_message, [*args[, **kwargs]])
exception(message[, *args])
log(log_level, log_message, [*args[, **kwargs]])
StreamHandler
FileHandler
RotatingFileHandler
TimedRotatingFileHandler
SocketHandler
DatagramHandler
SysLogHandler
NTEventLogHandler
SMTPHandler
MemoryHandler
HTTPHandler
LoggerFormatter, log的格式, 使用这个可以更容易的根据错误检错。
- %(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)
- %(lineno)d Source line number where the logging call was issued
- (if available)
- %(created)f Time when the LogRecord was created (time.time()
- return value)
- %(asctime)s Textual time when the LogRecord was created
- %(msecs)d Millisecond portion of the creation time
- %(relativeCreated)d Time in milliseconds when the LogRecord was created,
- relative to the time the logging module was loaded
- (typically at application startup time)
- %(thread)d Thread ID (if available)
- %(process)d Process ID (if available)
- %(message)s The result of record.getMessage(), computed just as
- the record is emitted
下面是一个简单的demo, 其中使用了两个handler分别将log记录到标准输出和文件中,因为handler是可以加多个的额, 所以你可以任意添加自己的handler。
- #!/usr/bin/env python
- import logging
- #create logger
- logger = logging.getLogger("simple_example")
- logger.setLevel(logging.DEBUG)
- #create console handler and set level to error
- ch = logging.StreamHandler()
- ch.setLevel(logging.ERROR)
- #create file handler and set level to debug
- fh = logging.FileHandler("spam.log")
- fh.setLevel(logging.DEBUG)
- #create formatter
- formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s -
- %(message)s")
- #add formatter to ch and fh
- ch.setFormatter(formatter)
- fh.setFormatter(formatter)
- #add ch and fh to logger
- logger.addHandler(ch)
- logger.addHandler(fh)
- #"application" code
- logger.debug("debug message")
- logger.info("info message")
- logger.warn("warn message")
- logger.error("error message")
- logger.critical("critical message")