Skip to main content

How to Use Logging in Python

A built-in module called Python log defines the classes and functions that implement the adaptable event-logging system for libraries and applications.

Logging is the process of storing information in a log file or printing into stdout, which can then be utilized for debugging if a problem arises.

Why Do We Need Log?

It is crucial to log in order to obtain the root cause analysis (RCA) of a problem if your code occasionally breaks and you are unable to figure out what caused the problem.

Although you can send the messages to stderr, using print for logging is not recommended.

You can also checkout other python tutorials:

Python Log

Python provides a built-in logging module that allows developers to track events in their applications and record any errors that occur. this is helpful in larger projects where it might be challenging to keep track of what’s going on behind the scenes.

How To Do Log in Python

Python log module provides a set of convenience functions for simple logging usage. In this article, we’ll go over the basics of using logging in Python.

import python log module

First, let’s start by importing the logging module:

import logging

Python Logging Levels

There are five levels of logging in Python, from highest to lowest:

  • CRITICAL
  • ERROR
  • WARNING
  • INFO
  • DEBUG

A simple example of logging

Let’s import the logging log module at the top of the file log.py file. We can use the following syntax to log a different variety of logs:

# log.py
import logging

logging.debug('This is a debug message')
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')

Output:

WARNING:root:This is a warning message
ERROR:root:This is an error message
CRITICAL:root:This is a critical message

The debug() and info() messages didn’t get logged. It is because, by default, the logging module logs the messages with the severity level of WARNING or above.

Logging Basic Configurations

We’ll set up a basic configuration for our logging. The severity of the messages that will be logged is determined by the logging level, which is also defined here.

The basicConfig(args) method is used to configure the logging in the python application. There are following parameters are used for this configuration:

logging.basicConfig(level=logging.DEBUG)
  • level: The root logger will be set to a specified severity level.
  • filename: This specifies the filename to log information.
  • filemode: The mode of the file if the file name is set, The default is, which means append.
  • form: This is the format of the log message.

The sample python log code

Let’s create a log.py file added a basic configuration for the python log.

import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

logger.info('Hello! pythonpip.com')

user = {'name': 'adam, 'age': 24}
logger.debug('Records: %s', user)
logger.info('Finished log')

You can also use debug(), info(), warning(), error(), and critical() method into the basicConfig(). By using a level parameter, you can set what level of log messages you want to record.

Output:

D:\workspace\python_workplace>py log.py
INFO:main:Hello! pythonpip.com
INFO:main:Finished log

Save Log Message into the File in Python

Sometimes, We need to log messages into the file instead of stdout. The basic configuration:

logging.basicConfig(filename='example.log', level=logging.DEBUG)

We can achieve something using python log module:

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

# create a file handler
handler = logging.FileHandler('info.log')
handler.setLevel(logging.INFO)

# create a logging format
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)

# add the handlers to the logger
logger.addHandler(handler)
logger.info('See the info.log file')

Every time you log a message, it will also be saved to the info.log file.

Output:

//info.log
2022-10-15 22:50:30,916 - main - INFO - See the info.log file

Logs With Aditional Information:

We can also include additional information such as the source of the message and a traceback for errors. The exc_info argument tells the logging module to include the traceback information in the log.

For example:

try:
    1/0
except Exception as e:
    logging.error("Error occurred: %s", e, exc_info=True)

One thought to “How to Use Logging in Python”

Leave a Reply

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