Skip to content

Instantly share code, notes, and snippets.

@andyshinn
Forked from M0r13n/README.md
Created June 22, 2024 00:14
Show Gist options
  • Save andyshinn/13442c639b391b435d94b55d8869244f to your computer and use it in GitHub Desktop.
Save andyshinn/13442c639b391b435d94b55d8869244f 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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment