A happy journey of simple Python: Journal of Python basic syntax

Defonds 2020-11-13 04:52:37
happy journey simple python journal


1. Python The log sample

Logs can help us monitor the running state of programs . Through the log we can see if the program raises any warnings or errors . We record time stamps 、 news 、 Stack and so on .
Before using any logging function in the program , You need to explicitly import Python Of logging library .

import logging
# then some logging statement(s)

Here are Python in logging An example of library usage .

import logging
logging.warning("This is a simple logging example")

Execution and output :
logging An example of library usage .jpg
Next let's learn about the different levels of logging 、 How to set the log level and so on .

2. Log messages to log files

Use Python Of logging modular , You can try it out 、 Information 、 Warning 、 error 、 Serious errors are recorded in the log file , Instead of just echoing to the console .
To record data into a file , Use logging The basic configuration of , Send the address of the log file to filename Parameters . If the file does not exist ,Python The system will create a new file , So you should assign the new and write permissions of the file in the directory where the file is located to start the Python Users of the program . Use logging Modular basicConfig() Function to set filename The basic syntax for parameters is as follows .

logging.basicConfig(filename="mylog.log")

You can rewrite the file name according to your own needs .

2.1. Record logging Message to log file

In the next example , We will use basicConfig() Function settings logging To configure , Log the message to a message named mylog.log External files for . If the full path is not provided , This file will be created in the program's execution directory .

# Python Example for Logging Messages to Log File
import logging
logging.basicConfig(filename="mylog.log")
logging.warning("This is a WARNING message")
logging.error("This is an ERROR message")
logging.critical("This is a CRITICAL message")

Execution and output :
 Record logging Message to log file .png
Check the current program directory , New documents found mylog.log Generate :
mylog.log Log file generation .png
View its contents :
 see mylog.log Content .png
so logging The message has been appended to the file .

2.3. Use handler Record logging Example of message to log file

This example is improved on the previous section , Used handler To handle the writing of log files .

# Python Example for Logging Messages to Log File using Handler
import logging
# create a logger
logger = logging.getLogger("mylogger")
handler = logging.FileHandler("mylog.log")
logger.addHandler(handler)
logger.warning("This is a WARNING message by handler")
logger.error("This is an ERROR message by handler")
logger.critical("This is a CRITICAL message by handler")

Execution and output :
 Use handler Record logging Example of message to log file .png
Check the log file again :
handler Use the log after execution and output .png
logging The message has been appended to the log file , But the format is slightly different from that in the previous section .

3. Print DEBUG Level of logging

To use logging Print a row DEBUG Level of logging ,

  • Check if the log level is at least DEBUG.
  • Use logging.debug() Method , Pass the message to it as a parameter , In order to DEBUG Line logs are printed to the console or log file .

When logging Level set to DEBUG in the future ,logging It will put DEBUG Line to print to console or log file .
When you set logging The level of INFOWARNINGERROR or CRITICAL when ,DEBUG The line will not be written to the log file .
logging The order of rank is :

DEBUG < INFO < WARNING < ERROR < CRITICAL

3.1. Print DEBUG Example of line

In this example , We will import logging modular , Set the log level to DEBUG, And then use debug() Method to print a DEBUG That's ok .

# Example to log DEBUG lines
import logging
# create a logger
logger = logging.getLogger("mylogger")
# set logging level
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler("mylog.log")
# create a logging format
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
# write a debug message
logger.debug("This is a debug message")

Check... After executing the program mylog.log
 Print DEBUG Example of line .png

3.2. Record only DEBUG Example of row

You can also be right handler Filter to print only DEBUG Line to log file .

# Example to log only DEBUG Lines using Python Logger
import logging
class MyFilter(object):
def __init__(self, level):
self.__level = level
def filter(self, logRecord):
return logRecord.levelno <= self.__level
# create a logger
logger = logging.getLogger("mylogger")
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler("mylog.log")
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
# set filter to log only DEBUG lines
handler.addFilter(MyFilter(logging.DEBUG))
logger.addHandler(handler)
# write a debug line to log file
logger.debug("This is a DEBUG message")
logger.info("This is a INFO message")
logger.warning("This is a WARNING message")
logger.error("This is an ERROR message")
logger.critical("This is a CRITICAL message")

Check... After executing the program mylog.log
 Record only DEBUG Example of row .png

4. logging INFO That's ok

To use Python logging Print INFO That's ok ,

  • Check logger Is the level at least INFO.
  • Use logging.info() Method , Pass the message to it as a parameter , In order to INFO Line logs are printed to the console or log file .

When logging Level set to INFO or DEBUG in the future ,logging It will put INFO Line to print to console or log file .
When you set logging The level of WARNINGERROR or CRITICAL when ,INFO The line will not be written to the log file .
logging The order of rank is :

DEBUG < INFO < WARNING < ERROR < CRITICAL

4.1. Print INFO Example of line

In this example , We will import logging modular , Set the log level to INFO, And then use info() Method to print a INFO That's ok .

# Example to log INFO lines
import logging
# create a logger
logger = logging.getLogger("mylogger")
# set logging level
logger.setLevel(logging.INFO)
handler = logging.FileHandler("mylog.log")
# create a logging format
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
# write a info message
logger.info("This is a INFO message")

Check... After executing the program mylog.log
 Print INFO Example of line .png

4.2. Record only INFO Example of row

You can also be right handler Filter to print only INFO Line to log file .

# Example to log only INFO Lines using Python Logger
import logging
class MyFilter(object):
def __init__(self, level):
self.__level = level
def filter(self, logRecord):
return logRecord.levelno == self.__level
# create a logger
logger = logging.getLogger("mylogger")
logger.setLevel(logging.INFO)
handler = logging.FileHandler("mylog.log")
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
# set filter to log only INFO lines
handler.addFilter(MyFilter(logging.INFO))
logger.addHandler(handler)
# write a INFO line to log file
logger.debug("This is a DEBUG message")
logger.info("This is a INFO message")
logger.warning("This is a WARNING message")
logger.error("This is an ERROR message")
logger.critical("This is a CRITICAL message")

Check... After executing the program mylog.log
 Record only INFO Example of row .png

5. logging WARNING That's ok

To use Python logging Print WARNING That's ok ,

  • Check logger Is the level at least WARNING.
  • Use logging.warning() Method , Pass the message to it as a parameter , In order to WARNING Line logs are printed to the console or log file .

When logging Level set to WARNINGINFO or DEBUG in the future ,logging It will put WARNING Line to print to console or log file .
When you set logging The level of ERROR or CRITICAL when ,WARNING The line will not be written to the log file .
logging The order of rank is :

DEBUG < INFO < WARNING < ERROR < CRITICAL

5.1. Print WARNING Example of line

In this example , We will import logging modular , Set the log level to WARNING, And then use warning() Method to print a WARNING That's ok .

# Example to log WARNING lines
import logging
# create a logger
logger = logging.getLogger("mylogger")
# set logging level
logger.setLevel(logging.WARNING)
handler = logging.FileHandler("mylog.log")
# create a logging format
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
# write a warning message
logger.warning("This is a WARNING message")

Check... After executing the program mylog.log
 Print WARNING Example of line .png

5.2. Record only WARNING Example of row

You can also be right handler Filter to print only WARNING Line to log file .

# Example to log only WARNING Lines using Python Logger
import logging
class MyFilter(object):
def __init__(self, level):
self.__level = level
def filter(self, logRecord):
return logRecord.levelno == self.__level
# create a logger
logger = logging.getLogger("mylogger")
logger.setLevel(logging.WARNING)
handler = logging.FileHandler("mylog.log")
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
# set filter to log only WARNING lines
handler.addFilter(MyFilter(logging.WARNING))
logger.addHandler(handler)
# write a WARNING line to log file
logger.debug("This is a DEBUG message")
logger.info("This is a INFO message")
logger.warning("This is a WARNING message")
logger.error("This is an ERROR message")
logger.critical("This is a CRITICAL message")

Check... After executing the program mylog.log
 Record only WARNING Example of row .png

6. logging ERROR That's ok

To use Python logging Print ERROR That's ok ,

  • Check logger Is the level at least ERROR.
  • Use logging.error() Method , Pass the message to it as a parameter , In order to ERROR Line logs are printed to the console or log file .

When logging Level set to ERRORWARNINGINFO or DEBUG in the future ,logging It will put ERROR Line to print to console or log file .
When you set logging The level of CRITICAL when ,WARNING Lines or lower will not be written to the log file .
logging The order of rank is :

DEBUG < INFO < WARNING < ERROR < CRITICAL

6.1. Print ERROR Example of line

In this example , We will import logging modular , Set the log level to ERROR, And then use warning() Method to print a ERROR That's ok .

# Example to log ERROR lines
import logging
# create a logger
logger = logging.getLogger("mylogger")
# set logging level
logger.setLevel(logging.ERROR)
handler = logging.FileHandler("mylog.log")
# create a logging format
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
# write an error message
logger.error("This is an ERROR message")

Check... After executing the program mylog.log
 Print ERROR Example of line .png

6.2. Record only ERROR Example of row

You can also be right handler Filter to print only ERROR Line to log file .

# Example to log only ERROR Lines using Python Logger
import logging
class MyFilter(object):
def __init__(self, level):
self.__level = level
def filter(self, logRecord):
return logRecord.levelno == self.__level
# create a logger
logger = logging.getLogger("mylogger")
logger.setLevel(logging.ERROR)
handler = logging.FileHandler("mylog.log")
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
# set filter to log only ERROR lines
handler.addFilter(MyFilter(logging.ERROR))
logger.addHandler(handler)
# write a ERROR line to log file
logger.debug("This is a DEBUG message")
logger.info("This is a INFO message")
logger.warning("This is a WARNING message")
logger.error("This is an ERROR message")
logger.critical("This is a CRITICAL message")

Check... After executing the program mylog.log
 Record only ERROR Example of row .png

7. logging CRITICAL That's ok

To use Python logging Print CRITICAL That's ok ,

  • Check logger Is the level at least CRITICAL.
  • Use logging.critical() Method , Pass the message to it as a parameter , In order to CRITICAL Line logs are printed to the console or log file .

When logging Level set to CRITICALERRORWARNINGINFO or DEBUG in the future ,logging It will put CRITICAL Line to print to console or log file .
When you set logging The level of CRITICAL when ,ERROR Lines or lower will not be written to the log file .
logging The order of rank is :

DEBUG < INFO < WARNING < ERROR < CRITICAL

7.1. Print CRITICAL Example of line

In this example , We will import logging modular , Set the log level to CRITICAL, And then use critical() Method to print a CRITICAL That's ok .

# Example to log CRITICAL lines
import logging
# create a logger
logger = logging.getLogger("mylogger")
# set logging level
logger.setLevel(logging.CRITICAL)
handler = logging.FileHandler("mylog.log")
# create a logging format
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
# write an CRITICAL message
logger.critical("This is a CRITICAL message")

Check... After executing the program mylog.log
 Print CRITICAL Example of line .png

Reference material

版权声明
本文为[Defonds]所创,转载请带上原文链接,感谢

  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