In Python, how dare you say you can't log module? ️

User 7227593569989 2021-08-09 12:42:19
python say log module


【 Abstract 】 Python in logging Detailed explanation of log module !

0. introduction :

  1. I believe many beginners Python My friends , When you encounter an error in your hard-working code , Do it yourself BUG Most of the methods are —— By adding a lot of print() function , A little narrowing down , Until I find BUG Location and solve it !

such as :
Pass below result1 To result5 Simulate the five functions painstakingly written by the partners , As a result, it was wrong when it finally called the ultimate function !
This is how to do —— Also good have print() function , Print one by one to see where the printing is abnormal :

result1 = ' The first function runs OK'
print(result1)
result2 = ' The second function runs OK'
print(result2)
result3 = ' The third function does not run OK'
print(result3)
result4 = ' The fourth function runs OK'
print(result4)
result5 = ' The fifth function runs OK'
print(result5)
 Copy code 

Undeniable? , This is indeed a solution BUG Methods ! however , When you find BUG After the location and resolution , So many printf() You have to delete them one by one , Is it too much trouble !

image.png

  1. therefore , Here we introduce logging modular . Let me use it briefly —— Let's look at the function of this module and its greatness !( Don't worry if you don't understand , The following text is a detailed explanation !)

We will all the above pirntf() The sentences are all changed to logging.debug() sentence , Observe the output , There is no output at this time —— That is, it has no impact on our procedures at present !

import logging
logging.basicConfig(level=logging.INFO)
result1 = ' The first function runs OK'
logging.debug(result1)
result2 = ' The second function runs OK'
logging.debug(result1)
result3 = ' The third function runs OK'
logging.debug(result1)
result4 = ' The fourth function runs OK'
logging.debug(result1)
result5 = ' The fifth function runs OK'
logging.debug(result1)
 Copy code 

 Insert picture description here

We set the log level to DEBUG, the level The value of the set logging.DEBUG, Then observe the output :

import logging
logging.basicConfig(level=logging.DEBUG)
result1 = ' The first function runs OK'
logging.debug(result1)
result2 = ' The second function runs OK'
logging.debug(result1)
result3 = ' The third function runs OK'
logging.debug(result1)
result4 = ' The fourth function runs OK'
logging.debug(result1)
result5 = ' The fifth function runs OK'
logging.debug(result1)
 Copy code 

Will find , At this point, it will be DEBUG Level output information . In this way, we can simply change the log level ( Just change one parameter value ) To control whether to output the display —— To check for errors , Instead of repeatedly adding and deleting print() Function to check for errors . Is it convenient ?

image.png

  1. I will try to make the technical text easy to understand / Lively and interesting , Make sure everyone wants to learn && Readers who read this article seriously can get something , Have gain . Of course , If you finish reading this article, you feel it's ok , Really learned something , Hope to give me a 「 Fabulous 」  and  「 Collection 」, This is for me Very important , Thank you for the !

The key! ! The key! !!

Now let's walk into logging The world of modules !!!

1.Logging modular

The first stage —— Basic use !

1. brief introduction :

It is a good habit to log the operation of programs in software development , It is very helpful for troubleshooting and system operation and maintenance .Python The standard library comes with a log module , The log function of the program directly calls the log module of the standard library through the log , Developers can clearly understand what happened , Including what went wrong .

2. The log level :

Be careful : After specifying the log level , Only log information greater than or equal to the specified log level will be displayed ! 

The log level (level) describe
DEBUG Debugging information , Usually used when diagnosing problems
INFO General information , Confirm that the program runs as expected
WARNING Warning message , Something unexpected happened , Or indicate that some problems may occur next , But the program continues to run
ERROR error message , There are some problems in the running of the program , Some functions of the program cannot be performed
CRITICAL Hazard information , A serious mistake , The program cannot continue

logging Medium level size :DEBUG<INFO<WARNING<ERROR<CRITICAL

3.formater Format :

image.png

4. The log level &format Format simulation uses :

import logging
# Format the output
LOG_FORMAT = " Time :%(asctime)s - The log level :%(levelname)s - Log information :%(message)s"
# Yes logger To configure —— The log level & Output format
logging.basicConfig(level=logging.WARNING, format=LOG_FORMAT)
# logging.level(message) Create a level Level of logging
logging.debug("This is a debug log")
logging.info("This is a info log")
logging.warning("This is a warning log")
logging.error("This is a error log")
logging.critical("This is a critical log")
 Copy code 

Observation can be seen , Indeed, only greater than or equal to WARNING Log level log information is output !

 Insert picture description here

Be careful :logging.basicConfig() There can only be one ! If you write more than one —— Only article 1 will take effect !!!

5. The log information is saved as a file :

The final log information used above is output at the terminal —— Once the computer is turned off / Program one off / Close the editor , The log information is lost !
And we won't do that in actual use , So let's see how to write a file !

image.png

tip : You can also specify filemode Parameter to specify how to write the file !( Analogy file operation a,a+ etc. )

image.png

The second stage —— Advanced version operation !

If it's just a simple use logging, Then use the method described above , If you want deep customization logging, Then we need to have a deeper understanding of it ! 

1.logging Modules also provide methods for modularizing components —— Flexible configuration of loggers :

Components explain
Loggers( Loggers ) The interface directly used by the provider ( In the basic operation logging.basicConfig() This component is configured )
Handlers( Log processor ) Send the recorded log to the specified location ( Terminal printing / Save as a file )
Filters( Log filter ) Used to filter specific log records
Formatters( Log formatter ) Used to control the output format of log information

The relationship between the components is shown in the figure below :

image.png

2. Modular components use :

(1) Use steps :

  1. Create a logger( Loggers ) object ;
  2. Definition handler( Log processor ), Decide where to send the log ;
    What is commonly used is :
    StreamHandler——> Output to console ;
    FileHandler——> output to a file ;
  3. Set the log level (level) And output format Formatters( Log formatter );
  4. hold handler Add to the corresponding logger In the middle .

(2) Use one in actual combat ( A logger corresponds to a log processor ):

import logging
# 1. Create a logger( Loggers ) object ;
my_logger = logging.Logger("first_logger")
# 2. Definition handler( Log processor ), Decide where to send the log ;
my_handler = logging.FileHandler('test.log')
# 3. Set the log level (level) And output format Formatters( Log formatter );
my_handler.setLevel(logging.INFO)
my_format = logging.Formatter(" Time :%(asctime)s Log information :%(message)s Line number :%(lineno)d")
# hold handler Add to the corresponding logger In the middle .
my_handler.setFormatter(my_format)
my_logger.addHandler(my_handler)
# Use :
my_logger.info(" I am the log component ")
 Copy code 

 Insert picture description here

(3) Use two in actual combat ( One logger corresponds to more than [ Here are two ] A log processor ):

import logging
# Create a logger( Loggers ) object ;
my_logger = logging.Logger("first_logger")
# The first log processor
my_handler = logging.FileHandler('test.log')
my_handler.setLevel(logging.INFO)
my_format = logging.Formatter(" Time :%(asctime)s Log information :%(message)s Line number :%(lineno)d")
my_handler.setFormatter(my_format)
my_logger.addHandler(my_handler)
# The second log processor
you_handler = logging.StreamHandler()
you_handler.setLevel(logging.DEBUG)
you_format = logging.Formatter(" Time :%(asctime)s Log information :%(message)s Line number :%(lineno)d This is a StreamHandler")
you_handler.setFormatter(you_format)
my_logger.addHandler(you_handler)
# Use :
my_logger.info(" I am the log component ")
 Copy code 

 Insert picture description here  Insert picture description here

2.In The End!

From now on , Hold the line , Make a little progress every day , Near future , You will thank you for your efforts !

版权声明
本文为[User 7227593569989]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/08/20210809123757157s.html

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database