python日志模块-Logging

日志配置

一般日志配置

为了在控制台规范的打印

import logging

# 日志配置
logging.basicConfig(level=logging.INFO, format='[%(asctime)s] - %(levelname)s in %(filename)s: %(message)s')

# 获取日志器
logger = logging.getLogger(__name__)

文件日志配置

写入文件的日志配置。

1. 旋转日志配置

写入文件,并且可以规定最大大小,自动滚动删除日志。

from logging.handlers import RotatingFileHandler
import logging

# Handler类,旋转文件日志,日志文件名,100MB,10个文件滚动
handler = RotatingFileHandler(filename='logs.log', maxBytes=100 * 1024 * 1024, backupCount=10)
# Formatter类
formatter = logging.Formatter('[%(asctime)s] - %(levelname)s in %(filename)s: %(message)s')
handler.setFormatter(formatter)  # 添加格式化实例
# 获取日志器
logger = logging.getLogger(__name__)
logger.addHandler(handler)
logger.setLevel(logging.INFO)  # 设置告警等级

2. 控制台打印日志

可以同时写文件也在控制台打印,主要是看选择哪些handler。

console = logging.StreamHandler()
logger.addHandler(console)  # 额外添加一个handler

scrapy写文件通用日志配置

import logging
from scrapy.utils.log import configure_logging

configure_logging(install_root_handler=False)
logging.basicConfig(
    filename='scrapy_log.txt',
    format='%(levelname)s: %(message)s',
    level=logging.INFO
)

日志打印

等级依次增高

logging.debug('debug message')
logging.info('info message')
logging.warn('warn message')
logging.error('error message')
logging.critical('critical message')

常用例子

import logging
import os
from logging.handlers import RotatingFileHandler


# 日志路径
LOG_PATH = 'log/'


# 日志等级
LOG_LEVEL = {
    'DEBUG': logging.DEBUG,
    'INFO': logging.INFO,
    'WARNING': logging.WARNING,
    'ERROR': logging.WARNING,
    'CRITICAL': logging.CRITICAL
}


def set_logger(log_name, level):
    """设置并返回日志器
    :param log_name:
    :param level:
    :return:
    """
    if not os.path.exists(LOG_PATH):
        os.makedirs(LOG_PATH)
    # Handler类,旋转文件日志,日志文件名,100MB,5个文件滚动
    handler = RotatingFileHandler(filename=LOG_PATH + '{}.log'.format(log_name), maxBytes=300 * 1024 * 1024,
                                  backupCount=5, encoding='utf-8')
    # Formatter类
    formatter = logging.Formatter('[%(asctime)s] - %(levelname)s in %(filename)s %(funcName)s: %(message)s')
    handler.setFormatter(formatter)  # 添加格式化实例
    # 获取日志器
    logger = logging.getLogger(log_name)
    logger.addHandler(handler)

    logger.setLevel(LOG_LEVEL.get(level, logging.INFO))  # 设置告警等级
    return logger
posted @ 2019-07-04 17:29  happy_codes  阅读(184)  评论(0编辑  收藏