Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
numpy.log10() in Python
Next article icon

Logging in Python

Last Updated : 02 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Logging is a means of tracking events that happen when some software runs. Logging is important for software developing, debugging, and running. If you don’t have any logging record and your program crashes, there are very few chances that you detect the cause of the problem. And if you detect the cause, it will consume a lot of time. With logging, you can leave a trail of breadcrumbs so that if something goes wrong, we can determine the cause of the problem. 

There are a number of situations like if you are expecting an integer, you have been given a float and you can a cloud API, the service is down for maintenance, and much more. Such problems are out of control and are hard to determine. 

Why print statement is not Pythonic

Some developers use the concept of printing the statements to validate if the statements are executed correctly or if some error has occurred. But printing is not a good idea. It may solve your issues for simple scripts but for complex scripts, the printing approach will fail.
Python has a built-in module logging which allows writing status messages to a file or any other output streams. The file can contain information on which part of the code is executed and what problems have arisen.  

Python Logging Levels

There are five built-in levels of the log message.  

  • Debug: These are used to give Detailed information, typically of interest only when diagnosing problems.
  • Info: These are used to confirm that things are working as expected
  • Warning: These are used as an indication that something unexpected happened, or is indicative of some problem in the near future
  • Error: This tells that due to a more serious problem, the software has not been able to perform some function
  • Critical: This tells serious error, indicating that the program itself may be unable to continue running

If required, developers have the option to create more levels but these are sufficient enough to handle every possible situation. Each built-in level has been assigned its numeric value.

The logging module is packed with several features. It has several constants, classes, and methods. The items with all caps are constant, the capitalized items are classes and the items which start with lowercase letters are methods. 

There are several logger objects offered by the base Handler itself.  

  • Logger.info(msg): This will log a message with level INFO on this logger.
  • Logger.warning(msg): This will log a message with a level WARNING on this logger.
  • Logger.error(msg): This will log a message with level ERROR on this logger.
  • Logger.critical(msg): This will log a message with level CRITICAL on this logger.
  • Logger.log(lvl,msg): This will Log a message with integer level lvl on this logger.
  • Logger.exception(msg): This will log a message with level ERROR on this logger.
  • Logger.setLevel(lvl): This function sets the threshold of this logger to lvl. This means that all the messages below this level will be ignored.
  • Logger.addFilter(filt): This adds a specific filter fit into this logger.
  • Logger.removeFilter(filt): This removes a specific filter fit into this logger.
  • Logger.filter(record): This method applies the logger’s filter to the record provided and returns True if the record is to be processed. Else, it will return False.
  • Logger.addHandler(hdlr): This adds a specific handler hdlr to this logger.
  • Logger.removeHandler(hdlr) : This removes a specific handler hdlr into this logger.
  • Logger.hasHandlers(): This checks if the logger has any handler configured or not. 

Useful Handlers

In addition to the base Handler Class, many useful subclasses are provided.

Handler

Description

StreamHandlerSends messages to streams (file-like objects).
FileHandlerSends messages to disk files.
BaseRotatingHandlerBase class for handlers that rotate log files at a certain point. Use RotatingFileHandler or TimedRotatingFileHandler instead.
RotatingFileHandlerSends messages to disk files, with support for maximum log file sizes and log file rotation.
TimedRotatingFileHandlerSends messages to disk files, rotating the log file at certain timed intervals.
SocketHandlerSends messages to TCP/IP sockets. Also supports Unix domain sockets since Python 3.4.
DatagramHandlerSends messages to UDP sockets. Also supports Unix domain sockets since Python 3.4.
SMTPHandlerSends messages to a designated email address.
SysLogHandlerSends messages to a Unix Syslogthe  daemon, possibly on a remote machine.
NTEventLogHandlerSends messages to a Windows NT/2000/XP event log.
MemoryHandlerSends messages to a buffer in memory, which is flushed whenever specific criteria are met.
HTTPHandlerSends messages to an HTTP server using either GET or POST semantics.
WatchedFileHandlerWatches the file it is logging to. If the file changes, it is closed and reopened using the file name.
QueueHandlerSends messages to a queue, such as those implemented in the queue or multiprocessing modules.
NullHandlerDoes nothing with error messages. Used by library developers to avoid ‘No handlers could be found for logger’ message.

Python Logging Basics

The basics of using the logging module to record the events in a file are very simple.  For that, simply import the module from the library.  

  1. Create and configure the logger. It can have several parameters. But importantly, pass the name of the file in which you want to record the events.
  2. Here the format of the logger can also be set. By default, the file works in append mode but we can change that to write mode if required.
  3. Also, the level of the logger can be set which acts as the threshold for tracking based on the numeric values assigned to each level. 
    There are several attributes that can be passed as parameters.
  4. The list of all those parameters is given in Python Library. The user can choose the required attribute according to the requirement.
    After that, create an object and use the various methods as shown in the example.

Logging a Variable 

This code demonstrates how to log an error message. The logging.error() function is used to log an error message with a placeholder %s for the variable name.

Python
import logging name = 'GFG' logging.error('%s raised an error', name) 

Output :

ERROR:root:GFG raised an error

Logging of all the levels 

This code demonstrates all the levels of logging.

Python
# importing module import logging  # Create and configure logger logging.basicConfig(filename="newfile.log",                     format='%(asctime)s %(message)s',                     filemode='w')  # Creating an object logger = logging.getLogger()  # Setting the threshold of logger to DEBUG logger.setLevel(logging.DEBUG)  # Test messages logger.debug("Harmless debug Message") logger.info("Just an information") logger.warning("Its a Warning") logger.error("Did you try to divide by zero") logger.critical("Internet is down") 

The above code will generate a file with the provided name and if we open the file, the file contains the following data. 

Python Logging Basics

Configuring Logging

Logging to a File: temp.conf 

[loggers]
keys=root,simpleExample

[handlers]
keys=consoleHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler

[logger_simpleExample]
level=DEBUG
handlers=consoleHandler
qualname=simpleExample
propagate=0

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s

Example:

The code sets up a logging system using the configuration from the temp.conf file. It obtains a logger named simple example and logs messages with various log levels.

Python
import logging import logging.config  logging.config.fileConfig('temp.conf')  # create logger logger = logging.getLogger('simpleExample')  # 'application' code logger.debug('debug message') logger.info('info message') logger.warning('warn message') logger.error('error message') logger.critical('critical message') 

Output :

2023-06-15 18:16:21 - simpleExample - DEBUG - debug message
2023-06-15 18:16:21 - simpleExample - INFO - info message
2023-06-15 18:16:21 - simpleExample - WARNING - warn message
2023-06-15 18:16:21 - simpleExample - ERROR - error message
2023-06-15 18:16:21 - simpleExample - CRITICAL - critical message

Python Logging Exception

Raising exceptions during logging can be useful in certain scenarios to indicate exceptional conditions or errors in your application. By raising an exception, you can halt the normal flow of execution and notify the caller or the logging system about the encountered issue.

In this code, we are raising an Exception that is being caught by the logging. exception.

Python
import logging  logging.basicConfig(level=logging.DEBUG,                     format='%(asctime)s - %(levelname)s - %(message)s')   def perform_operation(value):     if value < 0:         raise ValueError("Invalid value: Value cannot be negative.")     else:         # Continue with normal execution         logging.info("Operation performed successfully.")   try:     input_value = int(input("Enter a value: "))     perform_operation(input_value) except ValueError as ve:     logging.exception("Exception occurred: %s", str(ve)) 

Output :

Enter a value: -1
2023-06-15 18:25:18,064 - ERROR - Exception occurred: Invalid value: Value cannot be negative.

ValueError: Invalid value: Value cannot be negative.


Next Article
numpy.log10() in Python
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • Python
  • python
Practice Tags :
  • python
  • python

Similar Reads

  • numpy.log() in Python
    The numpy.log() is a mathematical function that helps user to calculate Natural logarithm of x where x belongs to all the input array elements. Natural logarithm log is the inverse of the exp(), so that log(exp(x)) = x. The natural logarithm is log in base e. Syntax :numpy.log(x[, out] = ufunc 'log1
    4 min read
  • Profiling in Python
    Python provides many excellent modules to measure the statistics of a program. This makes us know where the program is spending too much time and what to do in order to optimize it. It is better to optimize the code in order to increase the efficiency of a program. So, perform some standard tests to
    4 min read
  • numpy.log2() in Python
    numpy.log2(arr, out = None, *, where = True, casting = 'same_kind', order = 'K', dtype = None, ufunc 'log1p') : This mathematical function helps user to calculate Base-2 logarithm of x where x belongs to all the input array elements. Parameters : array : [array_like]Input array or object. out : [nda
    2 min read
  • numpy.log10() in Python
    About : numpy.log10(arr, out = None, *, where = True, casting = 'same_kind', order = 'K', dtype = None, ufunc 'log10') : This mathematical function helps user to calculate Base-10 logarithm of x where x belongs to all the input array elements. Parameters : array : [array_like]Input array or object.
    2 min read
  • numpy.log1p() in Python
    numpy.log1p(arr, out = None, *, where = True, casting = 'same_kind', order = 'K', dtype = None, ufunc 'log1p') : This mathematical function helps user to calculate natural logarithmic value of x+1 where x belongs to all the input array elements. log1p is reverse of exp(x) - 1. Parameters : array : [
    2 min read
  • numpy.logspace() in Python
    The numpy.logspace() function returns number spaces evenly w.r.t interval on a log scale. Syntax : numpy.logspace(start, stop, num = 50, endpoint = True, base = 10.0, dtype = None) Parameters : -> start : [float] start(base ** start) of interval range. -> stop : [float] end(base ** stop) of in
    2 min read
  • Print lists in Python
    Printing a list in Python is a common task when we need to visualize the items in the list. There are several methods to achieve this and each is suitable for different situations. In this article we explore these methods. The simplest way of printing a list is directly with the print() function: [G
    3 min read
  • Python Introduction
    Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code. Key Features of PythonPython’s simple and readable syntax makes it beginner-frie
    3 min read
  • numpy.logaddexp() in Python
    numpy.logaddexp() function is used to calculate Logarithm of the sum of exponentiations of the inputs. This function is useful in statistics where the calculated probabilities of events may be so small as to exceed the range of normal floating point numbers. In such cases, the logarithm of the calcu
    2 min read
  • Log functions in Python
    Python offers many inbuilt logarithmic functions under the module "math" which allows us to compute logs using a single line. There are 4 variants of logarithmic functions, all of which are discussed in this article.1. log(a,(Base)) : This function is used to compute the natural logarithm (Base e) o
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences