Last updated: Apr 11, 2024
Reading time·4 min
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.
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')
The
logging.basicConfig()
method creates a StreamHandler
with a default
Formatter
and adds it to the root logger.
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.
Level | Numeric Value |
---|---|
CRITICAL | 50 |
ERROR | 40 |
WARNING | 30 |
INFO | 20 |
DEBUG | 10 |
NOTSET | 0 |
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.
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')
The datefmt
argument is used to set the date/time format.
You can view all the available %
directives in
this section of the docs.
Directive | Meaning |
---|---|
%a | Locale's abbreviated weekday name. |
%A | Locale's full weekday name. |
%b | Locale's abbreviated month name. |
%B | Locale's full month name. |
%c | Locale's appropriate date and time representation. |
%d | Day of the month as a decimal. |
%H | Hour (24-hour clock) as a decimal. |
%I | Hour (12-hour clock) as a decimal number. |
%j | Day of the year as a decimal number. |
%m | Month as a decimal number. |
%M | Minute as a decimal number. |
%p | Locale's equivalent of AM or PM. |
%S | Second as a decimal number. |
%w | Week as a decimal number [0(Sunday), 6]. |
%x | Locale's appropriate date representation. |
%X | Locale's appropriate time representation. |
%y | Year without century as a decimal. |
%Y | Year 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.
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')
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
.
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')
You can read more about the basicConfig()
method in
this section of the docs.
You can also create a custom logger to print a timestamp for logging in Python.
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')
We used the
logging.Formatter
class to create a Formatter
object.
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.
file_handler = logging.FileHandler('log_file.txt', mode='w') file_handler.setFormatter(formatter)
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.
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.
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.
logger = create_logger('example-app') logger.info('Info message #1') logger.info('Info message #2')
You can learn more about the related topics by checking out the following tutorials: