logging模块

日志级别:

# CRITICAL(危险的,评定的)    FATAL(致命的) NOTSET(不设置)
# CRITICAL = 50
# FATAL = CRITICAL
# ERROR = 40
# WARNING = 30
# WARN = WARNING
# INFO = 20
# DEBUG = 10
# NOTSET = 0

格式:

   %(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)
    %(funcName)s        Function name
    %(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)
    %(threadName)s      Thread name (if available)
    %(process)d         Process ID (if available)
    %(message)s         The result of record.getMessage(), computed just as
                        the record is emitted
    """

 

单个日志文件:

#!/usr/bin/env python
# -*- encoding:utf-8 -*-
import logging

logging.basicConfig(filename='log.log', format=('%(asctime)s - %(name)s - %(levelname)s - %(module)s - %(message)s')
                    , datefmt='%Y-%m-%d %H:%M:%S %p', level=logging.DEBUG)
# 默认情况下,logging模块将日志打印到屏幕上(stdout),日志级别为WARNING(即只有日志级别高于WARNING的日志信息才会输出) 如果前面设置了配置则打印到文件中,不会打印到屏幕
logging.debug('debug message')
logging.info('info message')

# 警告  此方法过期了 最好不要使用
logging.warn('warn message')
logging.error('error message')
# 危险的
logging.critical('critical message')

多文件日志:

#!/usr/bin/env python
# -*- encoding:utf-8 -*-
import logging

# 定义文件
handler1 = logging.FileHandler('file1.log', 'a', encoding='utf-8')
fmt = logging.Formatter(fmt=('%(asctime)s - %(name)s - %(levelname)s - %(module)s - %(message)s'),
                        datefmt='%Y-%m-%d %H:%M:%S %p')
handler1.setFormatter(fmt)

handler2 = logging.FileHandler('file2.log', 'a', encoding='utf-8')
handler2.setFormatter(fmt)

# 定义日志
logger = logging.Logger('s1', level=logging.DEBUG)
logger.addHandler(handler1)
logger.addHandler(handler2)

# 写日志
logger.critical("写日志")

 

posted on 2018-01-20 20:56  jovelove  阅读(89)  评论(0)    收藏  举报