logging.StreamHandler
时间: 2024-02-05 07:03:15 浏览: 24
`logging.StreamHandler` is a class in the Python `logging` module that sends logging output to a stream (e.g. `sys.stdout`, `sys.stderr`, or a file-like object). It can be used to configure logging to send output to the console or to a file.
Here's an example of how to use it:
```python
import logging
# Create a logger
logger = logging.getLogger('example_logger')
logger.setLevel(logging.DEBUG)
# Create a stream handler and set its logging level to INFO
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)
# Add the stream handler to the logger
logger.addHandler(stream_handler)
# Log some messages
logger.debug('Debug message')
logger.info('Info message')
logger.warning('Warning message')
logger.error('Error message')
logger.critical('Critical message')
```
In this example, `logging.StreamHandler` is used to send logging output to the console. The `logger` object is created with a name of `'example_logger'` and its logging level is set to `DEBUG`. A stream handler is created with a logging level of `INFO`, which means that it will only handle messages with a severity level of `INFO` or higher. The stream handler is added to the logger, and then several messages are logged at different severity levels. Since the logger's logging level is set to `DEBUG`, all messages are processed by the logger and sent to the stream handler. The stream handler only outputs messages with a severity level of `INFO` or higher, so only the `INFO`, `WARNING`, `ERROR`, and `CRITICAL` messages are displayed on the console.