Python3 logging log package example

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

Python3 logging log package example
Python object-oriented example
Python3.7 debugging example method
Python interpolate interpolation example
Python negative modulus operation example
Python regular expression example code
Python output mathematical symbols example
Python iterable object de-duplication example
Python one-dimensional two-dimensional interpolation example
Python installation impala package steps
Python draw bar graph (bar graph) example
Explain how python references package package
Python right alignment example method
Python regular expression learning small example
Python calculation of information entropy example
Python waterfall line indicator writing example
Python list comprehension operation example summary
Python ATM function implementation code example
Usage of os package in python
Python example to calculate IV value
Install python package using Douban source
Python decorator simple usage example summary
Example operation of python access Alipay
Python tcp transmission code example analysis
Python requests module session code example
Python verification code interception identification code example