0

i need to change flask default logging handler to a custom JSON logging text, i can change handler before app.run() but flask set a default handler when I don't a standard handler (clear() logging handlers)

2 Answers 2

2

Just stumbled over a very convenient way to solve this challenge.

Go for json-logging package (https://github.com/bobbui/json-logging-python)

With that package installed, it's as easy as that:

import datetime, logging, sys, json_logging, flask

app = flask.Flask(__name__)
json_logging.init_flask(enable_json=True)
json_logging.init_request_instrument(app)

And proceed as usual in your Flask app.

Sign up to request clarification or add additional context in comments.

Comments

0
import logging
from pythonjsonlogger.jsonlogger import JsonFormatter

def get_logger(module_name):
    """Generate a logger."""
    logger = logging.getLogger(module_name)
    # logger.setLevel(logging.CRITICAL)
    logger.setLevel(logging.DEBUG)
    logger.propagate = False    # reset handler to avoid duplicates
    logger.handlers = [get_json_handler()]
    return logger


def get_json_handler():
    """Generate a JsonFormatter"""
    formatter = JsonFormatter("(asctime) (levelname) (module) (funcName) (lineno) (message)")
    log_handler = logging.StreamHandler()
    log_handler.setFormatter(formatter)
    return log_handler

# Example:
log = get_logger()

flask_log = logging.getLogger('werkzeug')
flask_log.setLevel(logging.DEBUG)
flask_log.addHandler(log)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.