python 的logging 的配置,有这一篇就够了

参考 文章:https://www.cnblogs.com/nwpuxuezha/p/9038172.html

python 自带


import logging

#输出的日志文件目录
LOG_FILE_NAME = "logs/log.log"

# 得到 logger 对象
logger = logging.getLogger()


# 初始化 logger
def log_init():
    # 输出的格式
    formatter = logging.Formatter(
        fmt='%(asctime)s  %(filename)s  [line:%(lineno)d]  %(levelname)s :%(message)s',
        datefmt='%Y-%m-%d %H:%M:%S')

    #设置级别
    logger.setLevel(logging.DEBUG)
    
    #控制台的输出
    ch = logging.StreamHandler()
    ch.setFormatter(formatter)

    # log文件的记录
    fh = logging.FileHandler(LOG_FILE_NAME)
    fh.setFormatter(formatter)

    #将输出的流 添加给logger
    logger.addHandler(ch)
    logger.addHandler(fh)


def test():
    logger.info("info")
    logger.error("error")

if __name__ == "__main__":
    log_init()
    test()

基于 YAML 的配置文件

version: 1
disable_existing_loggers: False
formatters:
    simple:
        format: "%(asctime)s - %(filename)s - %(lineno)s - %(levelname)s - %(message)s"

handlers:
    console:
        class: logging.StreamHandler
        level: INFO
        formatter: simple
        stream: ext://sys.stdout

    info_file_handler:
        class: logging.handlers.RotatingFileHandler
        level: INFO
        formatter: simple
        filename: logs/info.log
        maxBytes: 10485760 # 10MB
        backupCount: 20
        encoding: utf8

    error_file_handler:
        class: logging.handlers.RotatingFileHandler
        level: ERROR
        formatter: simple
        filename: logs/errors.log
        maxBytes: 10485760 # 10MB
        backupCount: 20
        encoding: utf8

    webdriver_handler:
        class: logging.handlers.RotatingFileHandler
        level: INFO
        formatter: simple
        filename: logs/webdriver.log
        maxBytes: 10485760 # 10MB
        backupCount: 20
        encoding: utf8

loggers:
    webdriver_module:
        level: INFO
        handlers: [console]
        propagate: no

root:
    level: INFO
    handlers: [console, info_file_handler, error_file_handler]



import logging.config
import os

import yaml

with open('logging.yaml') as f:
    if not os.path.exists('logs'):
        os.mkdir('logs')
    logging.config.dictConfig(yaml.safe_load(f.read()))


def get_logging(name=None):
    if name:
        return logging.getLogger(name)
    return logging


基于 JSON 的配置文件

posted @ 2020-10-14 15:16  西半球  阅读(1282)  评论(0编辑  收藏  举报