Skip to content

Python Logging Handler

  • by

In Python, a logging handler is an object that determines what happens to log records generated by the logging module. Handlers control where log records are sent and how they are formatted or processed. They provide a way to specify the output destination for log messages.

The syntax for creating a logging handler in Python is as follows:

import logging

# Create a logger
logger = logging.getLogger('my_logger')
logger.setLevel(logging.DEBUG)

# Create a handler
handler = logging.Handler()

# Set the log level for the handler
handler.setLevel(logging.INFO)

# Create a formatter and add it to the handler
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)

# Add the handler to the logger
logger.addHandler(handler)

The logging module in Python provides several built-in handler classes that handle different types of logging output. Here are some commonly used logging handler

HandlerDescription
StreamHandlerSends log records to a stream, such as sys.stdout or sys.stderr. Commonly used for displaying log messages on the console.
FileHandlerWrites log records to a file. Allows you to specify the filename and optionally the file mode (append or overwrite).
RotatingFileHandlerA variation of FileHandler that supports log file rotation based on size or time. Can create a new log file when the current file reaches a specified size or at certain time intervals.
TimedRotatingFileHandlerSimilar to RotatingFileHandler, but rotates log files based on specific time intervals, such as daily, hourly, or weekly.
SMTPHandlerSends log records via email. Useful for sending logs as email notifications.
SocketHandlerSends log records to a remote server via a socket connection. Can be used to centralize logs from multiple sources.
HTTPHandlerSends log records to a remote HTTP server. Useful for sending logs to a web application or logging service.
MemoryHandlerBuffers log records in memory and flushes them to a target handler once a specified buffer size is reached. Useful when immediate I/O is expensive, and you want to batch process log records.
NullHandlerA handler that does nothing. Useful for situations where you want to disable logging or suppress log messages.
QueueHandlerSends log records to a queue, allowing you to implement custom processing or routing of log records.
WatchedFileHandlerSimilar to FileHandler but also monitors the log file for changes. If the file is deleted or renamed, it will automatically switch to a new file with the same name when a new log record is received.

Python Logging Handler example

Here’s an example of how to use a logging handler in Python:

import logging

# Create a logger
logger = logging.getLogger('my_logger')
logger.setLevel(logging.DEBUG)

# Create a StreamHandler
stream_handler = logging.StreamHandler()

# Set the log level for the handler
stream_handler.setLevel(logging.INFO)

# Create a formatter and add it to the handler
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
stream_handler.setFormatter(formatter)

# Add the 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')

Output:

Python Logging Handler

In this example, we create a logger named 'my_logger' and set its log level to DEBUG. Then, we create a StreamHandler named stream_handler, which sends log records to a stream (in this case, the console).

We set the log level of the handler to INFO using stream_handler.setLevel(logging.INFO) to only handle messages with severity level INFO and above. You can choose the appropriate log level based on your requirements.

Next, we create a Formatter and configure it with the desired format for log records. In this case, '%(asctime)s - %(levelname)s - %(message)s' is used, which includes the timestamp, log level, and log message.

We add the formatter to the stream_handler using stream_handler.setFormatter(formatter).

Finally, we add the StreamHandler to the logger using the addHandler method. After that, we can use the logger to log messages at various severity levels. The log records will be processed by the handler, which will output them to the console with the configured format.

When you run this example, you will see the log messages printed to the console with the specified format.

Do comment if you have any doubts or suggestions on this Python logging topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *