Skip to content

Instantly share code, notes, and snippets.

@M0r13n
Last active July 25, 2024 23:53
Show Gist options
  • Save M0r13n/0b8c62c603fdbc98361062bd9ebe8153 to your computer and use it in GitHub Desktop.
Save M0r13n/0b8c62c603fdbc98361062bd9ebe8153 to your computer and use it in GitHub Desktop.
Logging with Loguru in Flask
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from config import config
from loguru import logger
import logging
db = SQLAlchemy()
# create a custom handler
class InterceptHandler(logging.Handler):
def emit(self, record):
logger_opt = logger.opt(depth=6, exception=record.exc_info)
logger_opt.log(record.levelno, record.getMessage())
# application factory pattern
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
db.init_app(app)
# logging properties are defined in config.py
logger.start(app.config['LOGFILE'], level=app.config['LOG_LEVEL'], format="{time} {level} {message}",
backtrace=app.config['LOG_BACKTRACE'], rotation='25 MB')
#register loguru as handler
app.logger.addHandler(InterceptHandler())
# register Blueprints here
# ...
return app

This is a simple example of how to use loguru in your flask application

Just create a new InterceptHandler and add it to your app. Different settings should be configured in your config file, so that it is easy to change settings.

Logging is then as easy as:

from loguru import logger

logger.info("I am logging from loguru!")

import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
SECRET_KEY = os.environ.get('SECRET_KEY') or 'SUPER-SECRET'
LOGFILE = "log.log"
class DevelopmentConfig(Config):
DEBUG = True
LOG_BACKTRACE = True
LOG_LEVEL = 'DEBUG'
class ProductionConfig(Config):
LOG_BACKTRACE = False
LOG_LEVEL = 'INFO'
config = {
'development': DevelopmentConfig,
'production': ProductionConfig,
'default': DevelopmentConfig
}
@martinenkoEduard
Copy link

How can I make FLASK automatically log all exception? (at least unhandled exceptions?)

@M0r13n
Copy link
Author

M0r13n commented Jul 15, 2022

@martinenkoEduard This is not possible natively. You need to define a custom exception hook instead. Here is an example: https://stackoverflow.com/questions/6234405/logging-uncaught-exceptions-in-python

@iamusera
Copy link

iamusera commented Dec 2, 2022

How can I make FLASK automatically log all exception? (at least unhandled exceptions?)

you can use @app.errorhandler(Exception) by custom exception hook

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment