Python log module Logging prints logs, outputs to files, and configures formats

Python Logging is a built-in logging module that allows you to log your application's debug information for easy troubleshooting during development and deployment.

log level

grade value illustrate
logging.CRITICAL 50 Critical error, indicating that the software cannot continue to run.
logging.ERROR 40 Error message that the software can no longer perform some functions due to more serious problems.
logging.WARNING 30 Default levels , notifications for some unforeseen events, or problems that may arise in the future. For example: Insufficient disk space. But the software will still work as usual.
logging.INFO 20 expected information
logging.DEBUG 10 debug information
logging.NOTSET 0 not set

Log level: debug < info < warning < error < critical
They all have corresponding functions to output to the console or file.

Print the log of the corresponding level:

import logging  
  
logging.basicConfig(level=logging.DEBUG)  
  
logging.debug('This is a debug message')  
logging.info('This is an info message')  
logging.warning('This is a warning message')  
logging.error('This is an error message')  
logging.critical('This is a critical message')

Use the basicConfig method to configure logging and set the log level to DEBUG.

Configure log format, output to file

logging.basicConfig(level=logging.DEBUG,  # 控制台打印的日志级别
                    filename='202308.log',
                    filemode='a',  # 模式,有w和a,w就是写模式,每次都会重新写日志,覆盖之前的日志
                    # a是追加模式,默认如果不写的话,就是追加模式
                    format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'
                    # 日志格式
2023-08-04 18:42:40,063 - D:\test1.py[line:12] - DEBUG: This is a debug message
2023-08-04 18:42:40,064 - D:\test1.py[line:13] - INFO: This is an info message
2023-08-04 18:42:40,064 - D:\test1.py[line:14] - WARNING: This is a warning message
2023-08-04 18:42:40,064 - D:\test1.py[line:15] - ERROR: This is an error message
2023-08-04 18:42:40,064 - D:\test1.py[line:16] - CRITICAL: This is a critical message

reference

https://docs.python.org/3/library/logging.html#logrecord-attributes

Guess you like

Origin blog.csdn.net/lilongsy/article/details/132110318