Python logging provides a way to track events that happen when some software runs. The logging module in Python is built-in and provides basic logging features. The logging.basicConfig() function is used to configure the logging module. The basicConfig() function can be used to configure the logging module with basic settings, such as the logging level, the output format, and the destination for log messages.
In this article, we will explore how to use the basicConfig() function to configure the logging module to write log messages to the standard output (stdout).
First, let's import the logging module and configure it using the basicConfig() function:
import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s')
In the above code, we have set the logging level to DEBUG, which means that all log messages with a level of DEBUG or higher will be output. The format parameter specifies the format of the log messages. The %(asctime)s, %(levelname)s, and %(message)s placeholders are used to display the timestamp, log level, and log message, respectively.
Once the logging module is configured, we can use the various logging functions to output log messages. For example, to output a DEBUG level log message, we can use the following code:
logging.debug('This is a debug message')
This will output the following log message to the stdout:
2022-01-29 12:34:56,789 DEBUG This is a debug message
Similarly, you can use the various logging functions such as info(), warning(), error() and critical() to output log messages of different levels.
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')
You can also use the logging.basicConfig() function to configure the logging module to output log messages to a file instead of the standard output. To do this, you need to set the filename parameter of the basicConfig() function to the path of the file where the log messages should be written. For example:
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', filename='example.log')
In this example, all log messages will be written to the example.log file in the current directory.
In conclusion, the logging module in Python provides a flexible and easy-to-use logging framework. The logging.basicConfig() function can be used to configure the logging module with basic settings, such as the logging level, the output format, and the destination for log messages. This article provided an example of how to use the basicConfig() function to configure the logging module to write log messages to the standard output (stdout) and also how to write log messages to a file.
The logging module in Python provides several other features that can be used to customize the logging behavior. One of the most powerful features is the ability to create custom log handlers. A log handler is an object that is responsible for writing log messages to a specific destination, such as a file or a network socket.
For example, you can create a custom log handler that sends log messages to a remote server over a network socket. To do this, you can create a new class that inherits from the logging.Handler class and overrides the emit() method to send log messages to the remote server. Here's an example of a custom log handler that sends log messages to a remote server:
import logging
import socket
class RemoteHandler(logging.Handler):
def __init__(self, host, port):
super().__init__()
self.host = host
self.port = port
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect((host, port))
def emit(self, record):
message = self.format(record)
self.socket.sendall(message.encode())
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s')
logging.getLogger().addHandler(RemoteHandler('example.com', 1234))
In this example, we have created a custom log handler called RemoteHandler that sends log messages to a remote server over a network socket. The host and port parameters passed to the constructor specify the destination server and port. The emit() method is overridden to send log messages to the remote server.
Another useful feature of the logging module is the ability to create log filters. A log filter is an object that can be used to determine if a log message should be output or not. For example, you can create a log filter that only outputs log messages that contain a specific string. Here's an example of a log filter that only outputs log messages that contain the string "example":
class ExampleFilter(logging.Filter):
def filter(self, record):
return "example" in record.getMessage()
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s')
logging.getLogger().addFilter(ExampleFilter())
In this example, we have created a custom log filter called ExampleFilter that only outputs log messages that contain the string "example". The filter() method is overridden to check if the log message contains the string "example". If it does, the log message is output, otherwise, it is discarded.
In addition, you can also configure the logging module to output log messages with different format based on the log level. This can be done by creating different formatters for different log levels. For example, you can create a formatter for DEBUG messages that includes more information than the formatter for INFO messages.
formatter_debug = logging.Formatter('%(asctime)s %(levelname)s %(module)s %(message)s')
formatter_info = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
logger = logging.getLogger()
debug_
## Popular questions
1. What is the `basicConfig()` function in Python's logging module used for?
- The `basicConfig()` function is used to configure the default behavior of the logging module. It sets the basic configuration for the root logger, such as the log level, the log format, and the destination for log messages.
2. How do you configure the logging module to output log messages to the standard output (stdout)?
- You can configure the logging module to output log messages to the standard output (stdout) by passing the `stream` parameter to the `basicConfig()` function and setting it to `sys.stdout`. Example: `logging.basicConfig(stream=sys.stdout)`
3. What is the difference between the `basicConfig()` function and the `basicConfig()` method?
- `basicConfig()` function is used to configure the default behavior of the logging module, while `basicConfig()` method is used to configure a specific logger. The method can be called on any logger object, not just the root logger.
4. How do you configure the logging module to output log messages with a specific format?
- You can configure the logging module to output log messages with a specific format by passing the `format` parameter to the `basicConfig()` function and setting it to a string that defines the desired format. The string can include placeholders for the log level, message, timestamp, etc. Example: `logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s')`
5. How do you change the logging level for a specific logger?
- You can change the logging level for a specific logger by calling the `setLevel()` method on that logger and passing the desired level as a parameter. Example: `logging.getLogger('mylogger').setLevel(logging.INFO)`
### Tag
Logging