Python Logging Basics - Simple Guide


Logging is used to track events that happen when a software runs. Using logging, you can add logging calls to their code to indicate that certain events have occurred. Through this, you can get to about error, information, warnings, etc.

Logging Functions

For logging, different functions are provided. You have to decide when the logging is to be used. For that, the following is provided by Python −

  • ogging.info() − Report events that occur during normal operation of a program.

  • logging.warning() − Issue a warning regarding a particular runtime event.

  • logging.error() − Report suppression of an error without raising an exception.

The standard level of severity of the events are shown below in increasing order of severity. These levels are DEBUG, INFO, WARNING, ERROR, CRITICAL −

  • DEBUG − This is Detailed information, typically of interest only when diagnosing problems.

  • INFO − Used when it is a confirmation that things working perfectly.

  • WARNING − This is the default level. It Indicates something unexpected happened or indicative of problems in future such as low memory, low disk space, etc.

  • ERROR − Due to a more serious problem, the software has not been able to perform some function.

  • CRITICAL − A serious error, indicating that the program itself may be unable to continue running.

Logging Example

Let us see a quick example −

import logging # Prints a message to the console logging.warning('Watch out!')

Output

WARNING:root:Watch out!

Default is Warning

As we explained above, the default level is warning. If you will try to print some other level, it won’t get printed −

import logging # Prints a message to the console logging.warning('Watch out!') # This won't get printed logging.info('Just for demo!')

Output

WARNING:root:Watch out!

Log Variable Data

To log variable data, you need to use a format string for the event description message and append the variable data as arguments.

import logging logging.warning('%s before you %s', 'Look', 'leap!')

Output

WARNING:root:Look before you leap!

Add date/time in log messages

When we talk about logging, the key is to include the date/time of the event as well. This is mainly to when the warning or error occurred −

import logging logging.basicConfig(format='%(asctime)s %(message)s') logging.warning('is the Log Time.')

Output

2022-09-19 17:42:47,365 is the Log Time.

Updated on: 20-Sep-2022

178 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements