EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials Flask Tutorial Flask logging
Secondary Sidebar
Flask Tutorial
  • Flask
    • Flask Version
    • Flask make_response
    • Flask WebSocket
    • Flask Session
    • Flask Environment Variables
    • Flask Cache
    • Flask Server
    • Flask jsonify
    • Flask logging
    • Flask redirect
    • Flask wtforms
    • Flask config
    • Flask Users
    • Flask upload file
    • Flask? get post data
    • Flask Template
    • Flask DB Migrate
    • Flask HTTPS
    • Flask bcrypt
    • Flask debug mode
    • Flask authentication
    • Flask Migrate
    • Flask URL Parameters
    • Flask API
    • Flask bootstrap
    • Flask POST request
    • Flask Extensions

Flask logging

Flask logging

Introduction to Flask logging

Flask logging is defined as a module that enables developers to implement a flexible, event logging system for Flask applications and includes all kinds of functions and classes that are necessary for the implementations. Logging in Flask uses the same standardized Python logging framework. The benefit of having a logging framework by standardized library module in Python is that all Python modules can interact and participate during logging. The messages are logged using app.logger and the Flask object instantiating is done with the same variable as that of app.name. This module provides a lot of functionality and flexibility to the developers of the Flask application.

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,950 ratings)

Syntax

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Logging is an essential part of any coding practice which allows developers to understand the flow of the program at a deeper level. With this deeper understanding comes the way of making the code running more transparent. With the below syntaxes we would get a sense of how it looks aesthetically before we jump on to learning about working of logging in our next section.

Instantiating the Python’s default logger (basicConfig):

import logging
logging.basicConfig(filename='<filename>.log', level=logging.<log_level>, format = '<message_structure>')

Setting the logging level to DEBUG:

<flask app name>.logger.debug("<Message that goes into the logger">)

Setting the logging level to INFO:

<flask app name>.logger.info("<Message that goes into the logger">)

Setting the logging level to WARNING:

<flask app name>.logger.warning("<Message that goes into the logger">)

Setting the logging level to ERROR:

<flask app name>.logger.error("<Message that goes into the logger">)

Setting the logging level to CRITICAL:

<flask app name>.logger.critical("<Message that goes into the logger">)

Removing the default handler:

<flask app name>.logger.removeHandler(default_handler)

Mailing errors to admins:

import logging
from logging.handlers import SMTPHandler
handlerSMTP = SMTPHandler(
mailhost=<host IP address>,
fromaddr='<from mail address>',
toaddrs=['<list of to address separated by comma>'],
subject='<subject of the mail>'
)
handlerSMTP.setLevel(logging.ERROR)
<flask app name>.logger.addHandler(handlerSMTP)

How does logging work in Flask?

To understand the working of logging in Flask we need to understand the different components as a part of the logging framework in Flask. The different components bind together the process of logging in Flask and make it a complete circle when it comes to working. These components are:

1. Logger: This is the entry point of any logging system which provides an interface to the Flask application for logging events for the application. The events which get recorded are known as log records. Each of the levels of record has its own severity and they are:

  • Debug: 10
  • Info: 20
  • Warning: 30
  • Error: 40
  • Critical: 50

Each of the log records consists of records matching to the severity of the levels mentioned above. Now a logger is configured to contain a log level. Any log record which has severity higher than that of the log level decided are only recorded in the logger. It is now, that the logger passes the log records to the handler.

2. Handlers: This component helps in directing the log events or records to be directed into their respective destination. By using different handlers, the events are routed to different files that might be even placed in multiple locations. If needed the logging framework might require multiple handlers to cater to the need of the application.

3. Formatters: After the logs are handled by handlers, the formatters are used for modifying the aesthetic feel and look of the log record. This component specifies the layout of the log record and is modified by mentioning the format of the log which is getting stored.

4. Filters: Finally, once the aesthetic look and feel is decided, this component helps developers on filtering the log record by parameters. These parameters can also be anything other than the log level.

 With the above 4 components the process flow of Flask logging is well understood but we are still left with some minute details regarding the working of logging in Flask. Flask application in background uses the python logging system framework for tracing the events during the application’s run time. In this article we will be mostly talking about using the Python’s default logger “BasicConfig”. If one feels the need to not use filename, the filename attribute can be removed, and the logs will be displayed to console itself but otherwise in presence of filename the log files are stored with .log extension. The last and final nail is the format which consists of various attributes so that proper message of log is stored and in a standardized way!

In our next section we will see the use of logging in a simple Flask application!

Examples

In this section we will look at all the uses of logging in a Flask application, as by now we have already looked at the syntax and the way of working of logging of Flask application. This will be a hands-on feel of the theoretical learning we did above.

Example #1

Instantiating the Python’s default logger (basicConfig)

Syntax

import logging
logging.basicConfig(level=logging.WARNING, format = 'Warning Structure Fomrat')

Output:

Flask logging output 1

Example #2

Setting the logging level to DEBUG

Syntax

from flask import Flask
appFlask = Flask(__name__)
@appFlask.route('/logLevel')
def logLevel():
appFlask.logger.debug("This is DEBUG log level")
return "Testing the debug log level"
if __name__ == "__main__":
appFlask.run(debug=True)

Output:

Flask logging output 2

Example #3

Setting the logging level to INFO

Syntax

from flask import Flask
appFlask = Flask(__name__)
@appFlask.route('/logLevel')
def logLevel():
appFlask.logger.info("This is INFO log level")
return "Testing the info log level"
if __name__ == "__main__":
appFlask.run(debug=True)

Output:

Flask logging output 3

Example #4

Setting the logging level to WARNING

Syntax

from flask import Flask
appFlask = Flask(__name__)
@appFlask.route('/logLevel')
def logLevel():
appFlask.logger.warning("This is WARNING log level")
return "Testing the warning log level"
if __name__ == "__main__":
appFlask.run(debug=True)

Output:

Flask logging output 4

Example #5

Setting the logging level to ERROR

Syntax

from flask import Flask
appFlask = Flask(__name__)
@appFlask.route('/logLevel')
def logLevel():
appFlask.logger.error("This is ERROR log level")
return "Testing the error log level"
if __name__ == "__main__":
appFlask.run(debug=True)

Output:

output 5

Example #6

Setting the logging level to CRITICAL

Syntax

from flask import Flask
appFlask = Flask(__name__)
@appFlask.route('/logLevel')
def logLevel():
appFlask.logger.critical("This is CRITICAL log level")
return "Testing the critical log level"
if __name__ == "__main__":
appFlask.run(debug=True)

Output:

output 6

Conclusion

In this article, we have got to know about the working of Flask logging and how it internally uses the Python logging framework. Along with that, we also took a dig into each of the levels separately so that one can understand the difference and use it as per their requirement. As usual, other experiments is left to readers to perform and learn!

Recommended Articles

This is a guide to Flask logging. Here we discuss the working of Flask logging and how it internally uses the Python logging framework. You may also have a look at the following articles to learn more –

  1. Flask HTTPS
  2. Flask Session
  3. Flask URL Parameters
  4. Flask Environment Variables
Popular Course in this category
Programming Languages Training (41 Courses, 13+ Projects, 4 Quizzes)
  41 Online Courses |  13 Hands-on Projects |  322+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more