logging.Formatter()
时间: 2024-05-03 10:22:34 浏览: 98
一个Format函数...
The `logging.Formatter()` class is used to customize the format of log messages. It provides a way to specify the format of the log message as well as the date and time format.
The `logging.Formatter()` class takes two arguments:
1. `fmt`: This is the format string for the log message. It specifies how the log message should be formatted.
2. `datefmt`: This is the format string for the date and time. It specifies how the date and time should be formatted.
Here is an example of how to use `logging.Formatter()`:
```python
import logging
# create a logger object
logger = logging.getLogger(__name__)
# create a formatter object
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# create a handler object
handler = logging.StreamHandler()
# set the formatter for the handler
handler.setFormatter(formatter)
# add the handler to the logger
logger.addHandler(handler)
# log a message
logger.info('This is a test message')
```
In this example, we create a logger object and a formatter object. We then create a handler object and set the formatter for the handler. Finally, we add the handler to the logger and log a message. The output of this code will be:
```
2021-08-26 11:08:01,123 - __main__ - INFO - This is a test message
```
The `%(asctime)s`, `%(name)s`, `%(levelname)s`, and `%(message)s` placeholders in the format string are replaced with the current date and time, the name of the logger, the log level, and the log message, respectively.
阅读全文