1.日志级别

python内置了logging模块,我们可以使用它记录自己的日志
日志级别:critical > error > warning > info > debug
当设置某个级别之后,把它低的不会被记录,例如级别设置为warning,则info和debug则会被丢弃

2.logging

如果记录要求不高不复杂,可以使用简单易用的logging

import logging

logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s', datefmt='%Y/%m/%d %H:%M:%S')  # 输出到控制台,设置格式
# logging.basicConfig(filename='test.log', filemode="a", level=logging.INFO)  # 输出到文件,默认是追加模式

logging.debug("输出debug")
logging.info("输出info")
logging.warning("输出warning")
logging.error("输出error")
logging.critical("输出critical")
3.logger

logging提供的用法比较单一,我们使用得更多的应该是更强大的logger
下面的例子是既能输出到控制台也可能输出到日志,就是创建2个handler分别处理不同的操作

import logging

# 创建logger对象
logger = logging.getLogger('my_logger')

# 设置日志等级
logger.setLevel(logging.INFO)
# 输出的日志信息格式
formatter = logging.Formatter('%(asctime)s-%(filename)s-line:%(lineno)d-%(levelname)s-%(process)s: %(message)s')

# 写到控制台
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
console_handler.setFormatter(formatter)

# 写到文件
file_handler = logging.FileHandler('test.log', encoding='utf-8')
file_handler.setLevel(logging.INFO)
file_handler.setFormatter(formatter)

# 保存到文件,但限制文件大小,会自动分割为多个日志文件
rotating_handler = handlers.RotatingFileHandler(filename='test2.log', maxBytes=1024 * 1024 * 300, encoding="utf-8")
rotating_handler.setLevel(logging.INFO)
rotating_handler.setFormatter(formatter)
new_logger.addHandler(rotating_handler)

# 设置到logger对象中
logger.addHandler(file_handler)
logger.addHandler(console_handler)
new_logger.addHandler(console_handler)

if __name__ == "__main__":
    logger.debug('this is debug message')
    logger.info('this is info message')
    logger.error("errorxxxxxxx")

:关于输出格式,可以参考官方的说明

"""

    %(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
"""
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐