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

原文地址:https://www.cnblogs.com/ucos/p/13820950.html