Gal Bracha
Gal Bracha

Reputation: 20021

In Flask: How to access app Logger within Blueprint

What is the standard way for a blueprint to access the application logger?

Upvotes: 75

Views: 30065

Answers (3)

Suresh Tupakula
Suresh Tupakula

Reputation: 1

In main(init).py file declare

dictConfig(
    {
        "version": 1,
        "formatters": {
            "default": {
                "format": "[%(asctime)s] [%(levelname)s | %(module)s] %(message)s",
                "datefmt": "%B %d, %Y %H:%M:%S",
            },
        },
        "handlers": {
            "console": {
                "class": "logging.StreamHandler",
                "formatter": "default",
            },
            "file": {
                "class": "logging.FileHandler",
                "filename": "ivt-trace.log",
                "formatter": "default",
            },
        },
        "root": {"level": "INFO", "handlers": ["console", "file"]},
    }
)

and in blueprint files :

import logging
from flask import current_app

logger = logging.getLogger(__name__)

# define the blueprint
blueprint_xxxx = Blueprint(name="blueprint_xxx", import_name=__name__, url_prefix='/xxxx/yyyy')

def some_func():
logger.info(msg="some logging info")

This worked for me.

Upvotes: 0

Gal Bracha
Gal Bracha

Reputation: 20021

Inside the blueprint add:

from flask import current_app

and when needed, call:

current_app.logger.info('grolsh')

Upvotes: 142

suzanshakya
suzanshakya

Reputation: 3650

Btw, I use this pattern:

# core.py
from werkzeug.local import LocalProxy
from flask import current_app

logger = LocalProxy(lambda: current_app.logger)


# views.py
from core import logger

@mod.route("/")
def index():
    logger.info("serving index")
    ...

Upvotes: 29

Related Questions