A complete program is inseparable from the log. Whether it is in the development phase, the test phase, or the program running phase, you can use the log to view the running status of the program or locate problems.
The following is the encapsulation of the logging library of python3, which should be able to meet most of the requirements. (If you are not satisfied, please leave a message below)
**Program structure: **
|- - logger.py
||- - singleton.py
||- - demo.py
||- - log
|||2018- 10- 12. log
logger.py
import os
import sys
import time
import logging
from singleton import Singleton
@ Singleton #If you need to print logs of different paths (run log, audit log), you cannot use the singleton mode (comment or delete this line). In addition, the parameter name needs to be set.
classLogger:
def __init__(self, set_level="INFO",
name=os.path.split(os.path.splitext(sys.argv[0])[0])[-1],
log_name=time.strftime("%Y-%m-%d.log", time.localtime()),
log_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),"log"),
use_console=True):"""
: param set_level:Log level["NOTSET"|"DEBUG"|"INFO"|"WARNING"|"ERROR"|"CRITICAL"], The default is INFO
: param name:The name printed in the log, the default is the name of the running program
: param log_name:The name of the log file, the default is the current time (year-month-day.log)
: param log_path:The path of the log folder, the default is logger.py log folder in the same level directory
: param use_console:Whether to print on the console, the default is True
"""
if not set_level:
set_level = self._exec_type() #Set_If level is None, the current operating mode is automatically obtained
self.__logger = logging.getLogger(name)
self.setLevel(getattr(logging, set_level.upper())ifhasattr(logging, set_level.upper())else logging.INFO) #Set log level
if not os.path.exists(log_path): #Create log directory
os.makedirs(log_path)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler_list =list()
handler_list.append(logging.FileHandler(os.path.join(log_path, log_name), encoding="utf-8"))if use_console:
handler_list.append(logging.StreamHandler())for handler in handler_list:
handler.setFormatter(formatter)
self.addHandler(handler)
def __getattr__(self, item):returngetattr(self.logger, item)
@ property
def logger(self):return self.__logger
@ logger.setter
def logger(self, func):
self.__logger = func
def _exec_type(self):return"DEBUG"if os.environ.get("IPYTHONENABLE")else"INFO"
singleton.py
classSingleton:"""
Singleton decorator.
"""
__ cls =dict()
def __init__(self, cls):
self.__key = cls
def __call__(self,*args,**kwargs):if self.__key not in self.cls:
self[self.__key]= self.__key(*args,**kwargs)return self[self.__key]
def __setitem__(self, key, value):
self.cls[key]= value
def __getitem__(self, item):return self.cls[item]
@ property
def cls(self):return self.__cls
@ cls.setter
def cls(self, cls):
self.__cls = cls
demo.py
import logger
x = logger.Logger("debug")
x.critical("This is a critical level question!")
x.error("This is an error level problem!")
x.warning("This is a warning level question!")
x.info("This is an info level question!")
x.debug("This is a debug level issue!")
x.log(50,"This is another way of writing a critical level question!")
x.log(40,"This is another way of writing an error level problem!")
x.log(30,"This is another way of writing a warning level question!")
x.log(20,"This is another way of writing an info level question!")
x.log(10,"This is another way of writing a debug level problem!")
x.log(51,"This is a Level 51 problem!")
x.log(11,"This is a Level 11 question!")
x.log(9,"The log level is lower than debug and will not be printed")
x.log(0,"This log will also not be printed")"""
operation result:
2018- 10- 1200:18:06,562- demo - CRITICAL -This is a critical level question!
2018- 10- 1200:18:06,562- demo - ERROR -This is an error level problem!
2018- 10- 1200:18:06,562- demo - WARNING -This is a warning level question!
2018- 10- 1200:18:06,562- demo - INFO -This is an info level question!
2018- 10- 1200:18:06,562- demo - DEBUG -This is a debug level issue!
2018- 10- 1200:18:06,562- demo - CRITICAL -This is another way of writing a critical level question!
2018- 10- 1200:18:06,562- demo - ERROR -This is another way of writing an error level problem!
2018- 10- 1200:18:06,562- demo - WARNING -This is another way of writing a warning level question!
2018- 10- 1200:18:06,562- demo - INFO -This is another way of writing an info level question!
2018- 10- 1200:18:06,562- demo - DEBUG -This is another way of writing a debug level problem!
2018- 10- 1200:18:06,562- demo - Level 51-This is a Level 51 problem!
2018- 10- 1200:18:06,562- demo - Level 11-This is a Level 11 question!
"""
2018- 10- 12. log
2018- 10- 1200:18:06,562- demo - CRITICAL -This is a critical level question!
2018- 10- 1200:18:06,562- demo - ERROR -This is an error level problem!
2018- 10- 1200:18:06,562- demo - WARNING -This is a warning level question!
2018- 10- 1200:18:06,562- demo - INFO -This is an info level question!
2018- 10- 1200:18:06,562- demo - DEBUG -This is a debug level issue!
2018- 10- 1200:18:06,562- demo - CRITICAL -This is another way of writing a critical level question!
2018- 10- 1200:18:06,562- demo - ERROR -This is another way of writing an error level problem!
2018- 10- 1200:18:06,562- demo - WARNING -This is another way of writing a warning level question!
2018- 10- 1200:18:06,562- demo - INFO -This is another way of writing an info level question!
2018- 10- 1200:18:06,562- demo - DEBUG -This is another way of writing a debug level problem!
2018- 10- 1200:18:06,562- demo - Level 51-This is a Level 51 problem!
2018- 10- 1200:18:06,562- demo - Level 11-This is a Level 11 question!
The above python3 logging log encapsulation example is all the content shared by the editor. I hope to give you a reference.
Recommended Posts