1. 程式人生 > >Python:使用配置檔案設定logger的配置(logging.config)

Python:使用配置檔案設定logger的配置(logging.config)

#!/usr/bin/env python
# coding:UTF-8


"""
@version: python3.x
@author:曹新健
@contact: [email protected]
@software: PyCharm
@file: 使用配置檔案設定logger的配置(logging.config).py
@time: 2018/11/16 13:26
"""

import os,logging,sys,time,json
import logging.config

def singleton(cls):
  instances = {}
  def _singleton(*args,**kwargs):
    if cls not in instances:
      instances[cls] = cls(*args,**kwargs)
    return instances[cls]
  return _singleton


@singleton
class Logger():
    def __init__(self,logfile=None):
        self.logger = logging.getLogger("simple_example")
        with open("logconf.json","r") as config:
            LOGGING_CONFIG = json.load(config)
            logging.config.dictConfig(LOGGING_CONFIG)


if __name__ == "__main__":
    lg = Logger()
    lg.logger.warning("aaa1")
    lg.logger.error("bbb2")
    lg.logger.debug("ccc3")
logconf.json


{
  "version":1,
  "handlers":{
    "console_streamHandler":{
      "class":"logging.StreamHandler",
      "level":"DEBUG",
      "formatter":"myFormatter",
      "stream":"ext://sys.stdout"
    },
    "console1_fileHandler":{
      "class":"logging.handlers.RotatingFileHandler",
      "level":"DEBUG",
      "formatter":"myFormatter",
      "filename":"log.log",
      "mode": "w+",
      "maxBytes":  524288000,
      "backupCount": 20,
      "encoding":"utf8"
    }
  },
  "formatters":{
    "myFormatter":{
      "format":"%(asctime)s %(name)s  %(levelname)s %(filename)s %(lineno)d %(thread)d %(threadName)s %(process)d %(message)s"
    }
  },
  "loggers":{
    "simple_example":{
      "level":"DEBUG",
      "handlers":["console_streamHandler","console1_fileHandler"]
    }
  }
}