How to print a Timestamp for Logging in Python

avatar
Borislav Hadzhiev

Last updated: Apr 11, 2024
4 min

banner

# Table of Contents

  1. How to print a Timestamp for Logging in Python
  2. Print a Timestamp for Logging by creating a custom logger in Python

# How to print a Timestamp for Logging in Python

Use the logging.basicConfig() method to print a timestamp for logging in Python.

The method creates a StreamHandler with a default Formatter and adds it to the root logger.

main.py
import logging import time logging.basicConfig( format='%(asctime)s %(levelname)-8s %(message)s', level=logging.DEBUG, datefmt='%Y-%m-%d %H:%M:%S' ) logging.info('Info message #1') time.sleep(2) logging.info('Info message #2') time.sleep(2) logging.debug('Debug message #1') time.sleep(2) logging.error('Error message #1') time.sleep(2) logging.warning('Warning message #1') time.sleep(2) logging.critical('Critical message #1')

print timestamp for logging in python

The code for this article is available on GitHub

The logging.basicConfig() method creates a StreamHandler with a default Formatter and adds it to the root logger.

main.py
logging.basicConfig( format='%(asctime)s %(levelname)-8s %(message)s', level=logging.DEBUG, datefmt='%Y-%m-%d %H:%M:%S' )

The format argument is used to set the format for the handler.

The argument defaults to the attributes levelname, name and message separated by colons.

The level argument is the root logger level.

LevelNumeric Value
CRITICAL50
ERROR40
WARNING30
INFO20
DEBUG10
NOTSET0

I set the level argument to logging.DEBUG, so that DEBUG, INFO, WARNING, ERROR and CRITICAL messages get printed.

For example, if you set the level to logging.INFO, then DEBUG messages won't get printed.

main.py
import logging logging.basicConfig( format='%(asctime)s %(levelname)-8s %(message)s', level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S', force=True ) logging.info('Info message #1') # 👇️ This won't print logging.debug('Debug message #1')

print timestamp for logging in python

The datefmt argument is used to set the date/time format.

You can view all the available % directives in this section of the docs.

DirectiveMeaning
%aLocale's abbreviated weekday name.
%ALocale's full weekday name.
%bLocale's abbreviated month name.
%BLocale's full month name.
%cLocale's appropriate date and time representation.
%dDay of the month as a decimal.
%HHour (24-hour clock) as a decimal.
%IHour (12-hour clock) as a decimal number.
%jDay of the year as a decimal number.
%mMonth as a decimal number.
%MMinute as a decimal number.
%pLocale's equivalent of AM or PM.
%SSecond as a decimal number.
%wWeek as a decimal number [0(Sunday), 6].
%xLocale's appropriate date representation.
%XLocale's appropriate time representation.
%yYear without century as a decimal.
%YYear with century as a decimal.

You can reorder the % directives in the string if you need to display the timestamp in a different way.

For example, the following code sample prints the timestamp for logging in the DD/MM/YYYY hh:mm:ss format.

main.py
import time import logging logging.basicConfig( format='%(asctime)s %(levelname)-8s %(message)s', level=logging.DEBUG, datefmt='%d/%m/%Y %H:%M:%S', force=True ) logging.info('Info message #1') time.sleep(2) logging.info('Info message #2')

print timestamp for logging in different format

The code for this article is available on GitHub

The debug(), info(), warning(), error() and critical() methods automatically call basicConfig() if no handlers are defined for the root logger.

The basicConfig() function does nothing if the root logger already has handlers configured, unless you set the force keyword argument to True.

main.py
import logging import time logging.basicConfig( format='%(asctime)s %(levelname)-8s %(message)s', level=logging.DEBUG, datefmt='%Y-%m-%d %H:%M:%S', force=True # 👈️ setting force to True ) logging.info('Info message #1') time.sleep(2) logging.info('Info message #2') time.sleep(2) logging.debug('Debug message #1') time.sleep(2) logging.error('Error message #1') time.sleep(2) logging.warning('Warning message #1') time.sleep(2) logging.critical('Critical message #1')
The code for this article is available on GitHub

You can read more about the basicConfig() method in this section of the docs.

# Print a Timestamp for Logging by creating a custom logger in Python

You can also create a custom logger to print a timestamp for logging in Python.

main.py
import logging import sys import time def create_logger(name): formatter = logging.Formatter( fmt='%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %H:%M:%S' ) file_handler = logging.FileHandler('log_file.txt', mode='w') file_handler.setFormatter(formatter) stream_handler = logging.StreamHandler(stream=sys.stdout) stream_handler.setFormatter(formatter) logger_ = logging.getLogger(name) logger_.setLevel(logging.DEBUG) logger_.addHandler(file_handler) logger_.addHandler(stream_handler) return logger_ logger = create_logger('example-app') logger.info('Info message #1') time.sleep(2) logger.info('Info message #2')

create custom logger to print timestamp for logging

The code for this article is available on GitHub

We used the logging.Formatter class to create a Formatter object.

main.py
formatter = logging.Formatter( fmt='%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %H:%M:%S' )

The Formatter object is initialized with a format string for the whole message and a format string for the date/time part of the message.

We used the logging.FileHandler class to open a file and use it as the stream for logging.

main.py
file_handler = logging.FileHandler('log_file.txt', mode='w') file_handler.setFormatter(formatter)

log file created

The file in the example is called log_file.txt but you can rename it as you see fit.

The next step is to use the logging.StreamHandler class to initialize the stream handler.

main.py
stream_handler = logging.StreamHandler(stream=sys.stdout) stream_handler.setFormatter(formatter)

The last step is to set the log level, the file handler and the stream handler.

main.py
logger_ = logging.getLogger(name) logger_.setLevel(logging.DEBUG) logger_.addHandler(file_handler) logger_.addHandler(stream_handler)

You can then create a logger and use the debug(), info(), warning(), error() and critical() methods to log messages with a timestamp.

main.py
logger = create_logger('example-app') logger.info('Info message #1') logger.info('Info message #2')

create custom logger to print timestamp for logging

The code for this article is available on GitHub

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.