• Home
  • HTML
    • HTML Introduction
    • HTML Basic
    • HTML Elements
    • HTML Attributes
    • HTML Headings
    • HTML Paragraphs
    • HTML Text Formatting
    • HTML Styles
    • HTML Comments
    • HTML Styles - CSS
    • HTML Links
    • HTML Images
    • HTML Tables
    • HTML Lists
    • HTML Block and Inline Elements
    • HTML class Attribute
    • HTML Forms
    • HTML Media
  • CSS
    • Introduction of CSS
    • CSS Syntax
    • CSS Selectors
    • How To Add CSS
    • CSS Comments
    • CSS Colors
    • CSS Backgrounds
    • CSS Borders
    • CSS Margins
    • CSS Text
    • CSS Lists
    • CSS Tables
    • CSS Box Model
    • CSS Dimension
    • CSS Padding
    • CSS Border
    • CSS Margin
    • CSS Outline
    • CSS Cursors
    • CSS Overflow
    • CSS Units
    • CSS Visual Formatting
    • CSS Display
    • CSS Visibility
    • CSS Position
    • CSS Layers
    • CSS Float
    • CSS Alignment
    • CSS Pseudo-classes
    • CSS Pseudo-elements
    • CSS Media Types
    • CSS Sprites
    • CSS Opacity
    • CSS Attribute Selectors
    • CSS Validation
    • CSS3 Border
    • CSS3 Gradients
    • CSS3 Text Overflow
  • JavaScript
    • JS Introduction
    • JS Getting Started
    • JS Syntax
    • JS Variables
    • JS Generating Output
    • JS Data Types
    • JS Operators
    • JS Events
    • JS Strings
    • JS Numbers
    • JS If Else
    • JS Switch Case
    • JS Arrays
    • JS Sorting Arrays
    • JS Loops
    • JS Functions
    • JS Objects
    • JS DOM Nodes
    • JS DOM Selectors
    • JS DOM Styling
    • JS DOM Get Set Attributes
    • JS DOM Manipulation
    • JS DOM Navigation
    • JS Window
    • JS Screen
    • JS Location
    • JS History
    • JS Navigator
    • JS Dialog Boxes
    • JS Timers
    • JS Date and Time
    • JS Math Operations
    • JS Type Conversions
    • JS Event Listeners
    • JS Event Propagation
    • JS Borrowing Methods
    • JS Hoisting Behavior
    • JS Closures
    • JS Strict Mode
    • JS JSON Parsing
    • JS Error Handling
    • JS Regular Expressions
    • JS Form Validation
    • JS Cookies
    • JS AJAX Requests
    • JS ES6 Features
  • jQuery
    • jQuery Introduction
    • jQuery Syntax
    • jQuery Selectors
    • jQuery Events
    • jQuery Show/Hide
    • jQuery Fade
    • jQuery Slide
    • jQuery Animation
    • jQuery Stop
    • jQuery Chaining
    • jQuery Callback
    • jQuery Get/Set
    • jQuery Insert
    • jQuery Remove
    • jQuery CSS Classes
    • jQuery Style Properties
    • jQuery Dimensions
    • jQuery Traversing
    • jQuery Ancestors
    • jQuery Descendants
    • jQuery Siblings
    • jQuery Filtering
    • jQuery Ajax
    • jQuery Load
    • jQuery Get/Post
    • jQuery No-Conflict
  • PHP
    • PHP Introduction
    • PHP Install
    • PHP Syntax
    • PHP Comments
    • PHP Variables
    • PHP Echo / Print
    • PHP Data Types
    • PHP Strings
    • PHP Constants
    • PHP Operators
    • PHP If...Else...Elseif
    • PHP Switch
    • PHP Loops
    • PHP Functions
    • PHP Arrays
    • PHP Superglobals
    • PHP Date and Time
    • PHP Include
    • PHP File Handling
    • PHP File Upload
    • PHP Cookies
    • PHP Sessions
    • PHP Filters
    • PHP Callback Functions
    • PHP JSON
    • PHP Exceptions
    • PHP What is OOP
    • PHP Classes/Objects
    • PHP Constructor
    • PHP Destructor
    • PHP Access Modifiers
    • PHP Inheritance
    • PHP Abstract Classes
    • PHP Interfaces
    • PHP Traits
    • PHP Static Methods
    • PHP Namespaces
  • SQL
    • Introduction to SQL
    • SQL Create Command
    • SQL ALTER Command
    • SQL Truncate Drop Rename
    • INSERT SQL command
    • UPDATE SQL command
    • DELETE SQL command
    • SQL COMMIT command
    • SQL ROLLBACK command
    • SQL GRANT and REVOKE Command
    • SQL WHERE clause
    • SQL LIKE clause
    • SQL ORDER BY Clause
    • SQL Group By Clause
    • SQL HAVING Clause
    • SQL DISTINCT keyword
    • SQL AND OR operator
    • SQL Constraints
    • SQL Functions
    • SQL JOIN
  • Python
    • Getting started with Python
    • Introduction to IDLE
    • Python 2.x vs. Python 3.x
    • Syntax Rules and First Program
    • Numbers and Math Functions
    • Python Operators
    • Python Variables
    • Python Modules and Functions
    • Python Input and Output
    • Data Types in Python
    • String in Python
    • String Functions in python
    • Lists in Python
    • Utilizing List Elements by Iterating
    • Deleting List Elements & other Functions
    • Dictionaries in Python
    • Functions for Dictionary
    • Tuples in Python
    • Relational and Logical Operators
    • Conditional Statements in Python
    • Looping in Python
    • Define Functions in Python
    • Python-Introduction to OOP
    • Object Oriented Programming in Python
    • Classes in Python
    • The concept of Constructor
    • Destructors - Destroying the Object in Python
    • Inheritance in Python
    • Access Modifers in Python
    • Types of Inheritance
    • Method Overriding in Python
    • Polymorphism
    • static Keyword
    • Operator Overloading Python
    • Introduction to Error Handling
    • Exception Handling: try and except
    • Exeption Handling: finally
    • Exception Handling: raise
    • File Handling
    • Reading and Writing File
    • Introduction to Multithreading
    • Threading Module in Python
    • Thread Object
    • Lock Object
    • RLock Object
    • Event Object
    • Timer Object
    • Condition Object
    • Barrier Object
    • __name__ Variable in Python
    • Iterable and Iterator
    • yield Keyword
    • Python Generators
    • Python Closures
    • Python Decorators
    • @property Decorator in Python
    • Assert Statement
    • Garbage Collection
    • Shallow and Deep Copy
    • Introduction to Logging
    • Configure Log LEVEL, Format etc
    • Python Logging in a file
    • Python Logging Variable Data
    • Python Logging Classes and Functions
    • Python MySQL Introduction
    • Create Database - Python MySQL
    • Create Table - Python MySQL
    • Insert Data in Table
    • Select Data from Table
    • Update data in Table
    • Delete data from Table
    • Drop Table from Database
    • WHERE clause - Python MySQL
    • Order By clause - Python MySQL
    • Limit clause - Python MySQL
    • Table Joins - Python MySQL
  • MongoDB
    • MongoDB Introduction
    • Overview of MongoDB
    • MongoDB vs SQL Databases
    • Advantages of MongoDB
    • When to go for MongoDB
    • Data Modelling in MongoDB
    • Is MongoDB really Schemaless?
    • Installing MongoDB on Windows and Linux
    • Datatypes in MongoDB
    • Create and Drop Database in MongoDB
    • MongoDB: Creating a Collection
    • CRUD Operations in MongoDB
    • Data Relationships in MongoDB
    • Indexing in MongoDB
    • Sorting in MongoDB
    • Aggregation in MongoDB
    • Data Backup and Restoration in MongoDB
    • Sharding in MongoDB
    • Java Integration with MongoDB
  • Elixir
    • Elixir Overview
    • Elixir Environment
    • Elixir Basic Syntax
    • Elixir Data Types
    • Elixir Variables
    • Elixir Operators
    • Elixir Pattern Matching
    • Elixir Decision Making
    • Elixir Strings
    • Elixir Char Lists
    • Elixir Lists and Tuples
    • Elixir Keyword Lists
    • Elixir Maps
    • Elixir Modules
    • Elixir Aliases
    • Elixir Functions
    • Elixir Recursion
    • Elixir Loops
    • Elixir Enumerables
    • Elixir Streams
    • Elixir Structs
    • Elixir Protocols
    • Elixir File I/O
    • Elixir Processes
    • Elixir Sigils
    • Elixir Comprehensions
    • Elixir Typespecs
    • Elixir Behaviours
    • Elixir Errors Handling
    • Elixir Macros
    • Elixir Libraries
  • TypeScript
    • TypeScript Overview
    • Install TypeScript
    • First TypeScript Program
    • Type Annotation
    • TypeScript Variable
    • TypeScript Data Type Number
    • TypeScript Data Type String
    • TypeScript Data Type Boolean
    • TypeScript Arrays
    • TypeScript Tuples
    • TypeScript Enum
    • TypeScript Union
    • TypeScript Any Data Type
    • TypeScript Void Data Type
    • TypeScript Never Data Type
  • Home
  • Getting started with Python
  • Introduction to IDLE
  • Python 2.x vs. Python 3.x
  • Syntax Rules and First Program
  • Numbers and Math Functions
  • Python Operators
  • Python Variables
  • Python Modules and Functions
  • Python Input and Output
  • Data Types in Python
  • String in Python
  • String Functions in python
  • Lists in Python
  • Utilizing List Elements by Iterating
  • Deleting List Elements & other Functions
  • Dictionaries in Python
  • Functions for Dictionary
  • Tuples in Python
  • Relational and Logical Operators
  • Conditional Statements in Python
  • Looping in Python
  • Define Functions in Python
  • Python-Introduction to OOP
  • Object Oriented Programming in Python
  • Classes in Python
  • The concept of Constructor
  • Destructors - Destroying the Object in Python
  • Inheritance in Python
  • Access Modifers in Python
  • Types of Inheritance
  • Method Overriding in Python
  • Polymorphism
  • static Keyword
  • Operator Overloading Python
  • Introduction to Error Handling
  • Exception Handling: try and except
  • Exeption Handling: finally
  • Exception Handling: raise
  • File Handling
  • Reading and Writing File
  • Introduction to Multithreading
  • Threading Module in Python
  • Thread Object
  • Lock Object
  • RLock Object
  • Event Object
  • Timer Object
  • Condition Object
  • Barrier Object
  • __name__ Variable in Python
  • Iterable and Iterator
  • yield Keyword
  • Python Generators
  • Python Closures
  • Python Decorators
  • @property Decorator in Python
  • Assert Statement
  • Garbage Collection
  • Shallow and Deep Copy
  • Introduction to Logging
  • Configure Log LEVEL, Format etc
  • Python Logging in a file
  • Python Logging Variable Data
  • Python Logging Classes and Functions
  • Python MySQL Introduction
  • Create Database - Python MySQL
  • Create Table - Python MySQL
  • Insert Data in Table
  • Select Data from Table
  • Update data in Table
  • Delete data from Table
  • Drop Table from Database
  • WHERE clause - Python MySQL
  • Order By clause - Python MySQL
  • Limit clause - Python MySQL
  • Table Joins - Python MySQL
Home >> python >> Introduction to Logging

Introduction to Logging

Welcome to another Print Logs in Python by using the Logging Module.

 

What is Logging?

In Python, logging is typically a way to track events, that is what is happening, and whenever any program/script runs. Also, the calls of logging are added by software developers in their software to print useful steps during software code execution along with information that can be used later to track down the execution.

  • Proper logging can help you develop a better understanding of the flow of the program and it is very helpful in discovering those scenarios that may not have been needed or thought of during development.
  • Logging is very useful in debugging problems in a program.
  • Logs help developers get an extra set of eyes to look at the flow of the application, as they can store information, like which user ID or IP is accessing the application.
  • It is used for logging user data and metrics in the software application. Errors can be debugged easily, however, you can also use the data to analyze the performance of the application to plan for scaling.
  • An event is described as a descriptive message that can optionally contain variable data, these are data, different for each occurrence of the event.
  • Events or Logs printed, also have importance, and are known as Log level.

 

Most new developers, use the print() method in their Python code to print statements and variables, to debug their code. However, making use of Logs is very much the right method for that.

 

Python Logging Module

In Python, the Logging module is an inbuilt module and is powerful and ready to use. Also, the module allows writing logs either to a file or console or to any other output stream.

In addition, this module is also, used by many third-party Python libraries. This is your project uses several third-party libraries, then you can use the logging module, as this log handling can be the same in your project and the third-party libraries you employed.

Check out the example to see how to write the above.

import logging

From the above example, after we imported the logging module, we can use the different methods provided by the logging module to print the logs.

 

Different Levels of Log Message

There are five standard levels by default in the Logging Module, which mainly indicate the severity of events. Thus, logging functions are named after the level. Check the illustration below for levels in order of increasing severity.

The table below shows the meaning of each level.

LevelTime to use
DEBUGIt is mainly used to provide detailed information, typically of interest only when debugging problems.
INFOIt is used to confirm that things are working as expected. That is the usual information.
WARNINGIt tells that something unexpected happened, but not too severe that it may affect the normal functioning of the program or software.
ERRORIt can be used to log more serious problems like errors or 1111exceptions leading to functionality getting broken.
CRITICALIt indicates a super serious error like the application not getting started or the database being unavailable to set up the connection and many more.

One can use any of the types of log levels in its python code to log different information.

An important question here is 'what logs will be printed', actually they depend on the configuration of the logging.

Note that the default level is a warning, meaning that only events of this level and above will be tracked, and they are warning, Error, and Critical.

 

Python Logging Methods

In Python some convenient functions are present for simple logging usage such as; debug(), info(), warning(), error() and critical(). They are discussed in the table below:

How to Log?Task to perform
print() methodIt is used to display normal messages on a console for the user information.
warning.warn() and logging.warn()

If you want to log a warning regarding a particular runtime event.

You can use the warning.warn() method in python code if the issue is avoidable and the changes must be made to eliminate the warning.

You can also, use the logging.warning() method in the case there is some small issue/error that doesn't have any direct impact on the functioning of the code, however, must be tracked as it may cause a problem later. E.g. a module version mismatch, and more.

Raise an Error/ExceptionThis report is an error regarding a particular runtime event.
logging.error() or logging.critical()

In this case, you desire to report without raising an exception. Also, if you have done proper exception handling, but, must still log the exception which is handled for it to be found later and fixed.

The method logging.critical() can be used for critical errors like program startup failed or database connection failed, and many more.

logging.info() or logging.debug()

The logging.info() method, is used to report events that occur during the normal operation of a program, for example, status monitoring or fault investigation.

The method logging.debug(),  is typically used for very detailed output for diagnostic purposes.

 

Logging Example in Python

Check out this example, in which we will use the print log messages related to the different log levels.

import logging

logging.debug('It is a debug message')	# it will not be printed
logging.info('It is an info message')	# not printed
logging.warning('OOPs!!! It is a warning')	# it will be print because it is default level
logging.error('Oops !! an error message')	# will be printed 
logging.critical('Oh!!!! it is a critical message')	# will be printed

Output:

WARNING:root: OOPs!!! It is a warning
ERROR:root: Oops !! an error message
CRITICAL:root: Oh!!!! it is a critical message

The output for the code above shows the severity level before each message along with the root. The root is the name that the logging module gives to its default logger.

In addition, the output format illustrates the level, name, and message, and all are separated by a colon(:) and thus is the default format for logs, but the format can be changed.

Note that the debug() and info() messages did not get logged. This is because, by default, the logging modules log the messages with a severity level of warning or just as mentioned above.

However, we can change that by configuring the logging module to log events of all levels if it is needed again.

 

 

  • Prev
  • Next


-Advertisement-


DeveloperTutorial
[email protected] © 2022-2023 Developers Tutorial All rights reserved.

Follow Us

Facebook Twitter LinkedIn Printerest Reddit

Announcement

Its a big achivement for us, We make a partnership with TutorialWithExample.com for the better content of our users.

Still Need Help ?

Let us now about your issue and a Professional will reach you out.