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.运行结果

  • 相关阅读:
    [转载]备忘:oh my zsh 的安装、更新、删除
    【转载】fedora22和win10之间的文件共享互访
    python3.7[列表] 索引切片
    注册科创版 等待生效中 测评 投资
    谷歌镜像-20190627
    debian静态地址网络配置方法
    latex高速新手教程
    Java知识点解析
    【Linux 操作系统】Ubuntu 配置 ftp freemind adb
    vs2012设置默认的全局include和lib
  • 原文地址:https://www.cnblogs.com/ucos/p/13820950.html
Copyright © 2011-2022 走看看