Python 记录日志 | logging + yaml

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011262253/article/details/80242982

1. 模块安装

pip install logging
pip install pyyaml

2. 使用

2.1 创建配置文件

创建名为 logging.config.yaml 文件, 内容如下:

version: 1
disable_existing_loggers: False
formatters:
        simple:
            format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
handlers:
    console:
            class: logging.StreamHandler
            level: DEBUG
            formatter: simple
            stream: ext://sys.stdout
    info_file_handler:
            class: logging.handlers.RotatingFileHandler
            level: INFO
            formatter: simple
            filename: info.log
            maxBytes: 10485760
            backupCount: 20
            encoding: utf8
    error_file_handler:
            class: logging.handlers.RotatingFileHandler
            level: ERROR
            formatter: simple
            filename: errors.log
            maxBytes: 10485760
            backupCount: 20
            encoding: utf8
loggers:
    my_module:
            level: ERROR
            handlers: [info_file_handler]
            propagate: no
root:
    level: INFO
    handlers: [console,info_file_handler,error_file_handler]

logging 的配置:https://docs.python.org/2/library/logging.config.html

2.2 在Python脚本中使用

# !/usr/bin/env python
# -- coding: utf-8 --
# @Time : 2018/4/27 20:16
# @Author : Baimoc

import logging.config
import yaml

# 日志文件配置
def get_logger():
    log_conf = 'logging.config.yaml'
    with file(log_conf, 'rt') as f:
        config = yaml.safe_load(f.read())
    logging.config.dictConfig(config)
    return logging.getLogger()
if __name__ == '__main__':
    logger = get_logger()
    logger.info(">>> Check Program paths")
    logger.error(soft_name + " program not found, please edit the configuration script.")

猜你喜欢

转载自blog.csdn.net/u011262253/article/details/80242982