Python is a widely used programming language with a wealth of libraries and modules that allow developers to develop programs more efficiently. Among them, the logging module is widely used for logging. This article will introduce how to use the logging module for logging in Python 2.x, with code examples.
First, we need to import the logging module of Python. Add the following statements to the code:
import logging
Before starting logging, we need to perform some configurations on the logging module. These configuration options include log format, level, etc. The following sample code shows a basic configuration:
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', filename='app.log', filemode='w')
In this example, we set the log level to debug level (DEBUG) and define the format of the log. The log level setting can be adjusted according to actual needs. The format parameter defines the format of the log output, including date, log level and log message. The filename parameter sets the name of the log file, and the filemode parameter defines the opening mode of the log file ('w' means overwrite writing).
After the configuration is completed, we can use the logging module to output log information. The following are some commonly used log levels and corresponding output methods:
The sample code is as follows:
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')
According to the above configuration and code, the log will be written to a file named "app.log". The following is the content of a sample log file:
2019-01-01 14:35:26,572 DEBUG This is a debug message 2019-01-01 14:35:26,572 INFO This is an info message 2019-01-01 14:35:26,572 WARNING This is a warning message 2019-01-01 14:35:26,572 ERROR This is an error message 2019-01-01 14:35:26,572 CRITICAL This is a critical message
We can see that each log has a timestamp, followed by the log level and message content.
The above is the basic method of using the logging module for logging in Python 2.x. By configuring the logging module and using the corresponding output method, we can easily record and track the running process of the program, allowing for better debugging and error handling. In actual development, we can customize and expand the logging module more as needed to meet different logging needs.
The above is the detailed content of How to use the logging module for logging in Python 2.x. For more information, please follow other related articles on the PHP Chinese website!