zoukankan      html  css  js  c++  java
  • Python Logging 日志配置文件

    1.项目结构

    2.配置文件,LogConfigure.json

    {
      "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": "FileLoges/info.log",
          "maxBytes": 10485760,
          "backupCount": 20,
          "encoding": "utf8"
        },
        "error_file_handler": {
          "class": "logging.handlers.RotatingFileHandler",
          "level": "ERROR",
          "formatter": "simple",
          "filename": "FileLoges/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"
        ]
      }
    }

    3.测试代码,main.py

    import os
    import json
    import logging.config
    
    
    def configure_logging(configure_file_path="LogConfigure.json", default_level=logging.INFO, env_key="LOG_CFG"):
        path = configure_file_path
        value = os.getenv(env_key, None)
        if value:
            path = value
        if os.path.exists(path):
            with open(path, "r") as f:
                config = json.load(f)
                logging.config.dictConfig(config)
        else:
            logging.basicConfig(level=default_level)
    
    
    def set_log_info():
        logging.info("Let's start to log some information.")
    
        logging.error("There are so many errors.")
    
    
    if __name__ == "__main__":
        configure_logging("LogConfigure.json")
        set_log_info()

    4.运行结果

  • 相关阅读:
    Docker安装及基本命令
    SpringBoot-获取YAML文件值
    SpringBoot-YAML语法
    Maven仓库
    第一次使用Maven
    初始Maven
    索引的基本使用与创建选择
    了解索引为什么能快速查找数据
    Mysql的执行顺序与优化分析
    Mysql常用的几种join连接方式
  • 原文地址:https://www.cnblogs.com/ucos/p/13820950.html
Copyright © 2011-2022 走看看