How to Customize the time format for Python logging?

Better Stack Team
Updated on August 25, 2023

To customize the time format for Python logging, you need to modify the formatter used by the logging module. Python's logging module provides a powerful mechanism to control the log message formatting, including the timestamp format. You can use the logging.Formatter class to create a custom formatter and set it to the desired time format.

The time format follows the same syntax as the time.strftime() function, where you can use specific placeholders for different components of the timestamp, such as year, month, day, hour, minute, second, etc.

Here's an example of how to customize the time format for Python logging:

 
import logging

# Create a custom formatter with your desired time format
time_format = "%Y-%m-%d %H:%M:%S"
formatter = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(message)s', datefmt=time_format)

# Create a logger and set the custom formatter
logger = logging.getLogger('custom_logger')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)

# Set the log level (optional, can be DEBUG, INFO, WARNING, ERROR, CRITICAL)
logger.setLevel(logging.DEBUG)

# Now you can use the logger to log messages with your custom time format
logger.debug('This is a debug message')
logger.info('This is an info message')
logger.warning('This is a warning message')
logger.error('This is an error message')
logger.critical('This is a critical message')

In this example, the time_format variable is set to "%Y-%m-%d %H:%M:%S", which will produce a timestamp in the format "YYYY-MM-DD HH:MM:SS".

The logging.Formatter class takes two arguments: fmt for the log message format (including placeholders for the timestamp), and datefmt for the custom time format.

By using this approach, you can easily customize the time format according to your preference and requirements. The logging module will then use your custom formatter to format the log messages, including the timestamp, based on the specified time format.

To learn more about logging in Python, visit Better Stack Community.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github