search
HomeBackend DevelopmentPython TutorialDetailed explanation of Python's implementation of Logger printing function

Recently I encountered the need for printing at work. By searching for relevant information, I found that Logger in Python can implement printing very well, so the following article mainly introduces you to the relevant information on how Python implements the Logger printing function. In the article The introduction through sample code is very detailed, friends in need can refer to it.

Preface

As we all know, there is a suite specifically for logger printing in Python called logging, but the logger in this suite only receives a string type The logger prints information. Therefore, we need to concatenate the information to be printed into a string in advance before using it, which is not good for the cleanliness of the code.

Based on logging, I implemented a logger printing tool similar to Java's logback. The implementation is relatively simple and can handle some simple logger printing needs. I hope it can be helpful to everyone. Not much to say below, let’s take a look at the detailed introduction:

LoggerFactory

This class is used to generate loggers for other calling classes. instances and save those instances.


'''
Created on 2017年7月20日
Logger工厂,保存每个类的Logger实例
'''
from slient.bigdata.common.logger import Logger
import logging

class LoggerFactory :
 LOG_FILENAME='bigdata_python.log' #logger保存文件
 TYPE = "CONSOLE"     #logger打印类型
 #TYPE = "FILE"

 LEVEL = logging.DEBUG    #logger级别
 #LEVEL = logging.INFO

 loggerDict = {}

 #对外部开放的Logger调用方法
 @staticmethod
 def getLogger(className) -> Logger:
  if className in LoggerFactory.loggerDict.keys() : 
   logger = LoggerFactory.loggerDict[className]
   if not logger : 
    logger = LoggerFactory.__initLogger(className)
  else : 
   logger = LoggerFactory.__initLogger(className)
  return logger

 #生成Logger实例
 @staticmethod
 def __initLogger(className) -> Logger: 
  logger = logging.getLogger(className)
  # 设置logger的level为DEBUG
  logger.setLevel(LoggerFactory.LEVEL)
  #设置Logger格式
  formatter = logging.Formatter('[%(asctime)s] [%(name)s] [%(levelname)s]: %(message)s')

  if LoggerFactory.TYPE == 'CONSOLE' : 
   # 创建输出日志到控制台的StreamHandler
   handler = logging.StreamHandler()
  else : 
   # 创建输出日志到文件Handler
   handler = logging.FileHandler(LoggerFactory.LOG_FILENAME)

  #添加格式 
  handler.setFormatter(formatter)
  # 给logger添加上handler
  logger.addHandler(handler)

  localLogger = Logger(logger)
  LoggerFactory.loggerDict[className] = localLogger
  return localLogger

Logger

This class mainly implements the encapsulation of some logging methods ,easier.


'''
Created on 2017年7月5日
日志处理
'''
import logging
import string

class Logger :

 def __init__(self, logger : logging):
  self.logger = logger

 def info(self, formatStr:string, *objs):
  self.logger.info(formatStr.format(*objs))

 def debug(self, formatStr:string, *objs):
  self.logger.debug(formatStr.format(*objs))

 def error(self, formatStr:string, *objs):
  self.logger.error(formatStr.format(*objs))

Test


logger = LoggerFactory.getLogger("Test")
logger.info("打印log1:{}, 打印log2:{}", 666, "我是log2")

Test result:


[2017-07-20 16:43:00,821] [Test] [INFO]: 打印log1:666, 打印log2:我是log2

The above is the detailed content of Detailed explanation of Python's implementation of Logger printing function. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Merging Lists in Python: Choosing the Right MethodMerging Lists in Python: Choosing the Right MethodMay 14, 2025 am 12:11 AM

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

How to concatenate two lists in python 3?How to concatenate two lists in python 3?May 14, 2025 am 12:09 AM

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Python concatenate list stringsPython concatenate list stringsMay 14, 2025 am 12:08 AM

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

Python execution, what is that?Python execution, what is that?May 14, 2025 am 12:06 AM

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Python: what are the key featuresPython: what are the key featuresMay 14, 2025 am 12:02 AM

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools