yaml文件配置logger

yaml

今天用yaml文件写了一下logging的配置,文件如下:

version: 1
disable_existing_loggers: False
formatters:
    simple:
        format: "%(asctime)s - %(filename)s - %(levelname)s - %(message)s"
handlers:
    console:
        class: logging.StreamHandler
        level: ERROR
        formatter: simple
        stream: ext://sys.stdout

    info_file_handler:
        class: logging.handlers.RotatingFileHandler
        level: INFO
        formatter: simple
        filename: ./mylog/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: [console]
        propagate: no

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

只是做个demo,所以写的比较粗略,然后中间就是包含了formatter,handlers,并没有使用filters,最终的效果是ERROR级别的信息将会在命令台进行打印并写入日志文件当中。

try_log.py

# -*- coding: utf-8 -*-


import os
import yaml
import logging
from logging import config as logger_config


config_file = os.path.join(os.path.dirname(__file__), "config.yaml")

if os.path.exists("mylog"):
    pass
else:
    os.mkdir("mylog")

with open(config_file, "rt") as stream:
    config = yaml.unsafe_load(stream.read())

logger_config.dictConfig(config)
logger = logging.getLogger()


if __name__ == "__main__":
    logger.error("This is a test error message for my first logger.")

运行这个命令就可以看到相应的结果了。
1289497-20190415224841924-103866209.png

1289497-20190415224913732-282322803.png

转载于:https://www.cnblogs.com/zzy0306/p/10713926.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值