Created
February 27, 2017 17:41
-
-
Save reallistic/f094b9e4205c413aa93f5e4fbd96017e to your computer and use it in GitHub Desktop.
Example logging setup with python flask
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
from flask import Flask | |
from threading import Lock | |
# a lock used for logger initialization | |
_logger_lock = Lock() | |
class MyCustomLogger(object): | |
def __init__(self, app): | |
self.instance = logging.getLogger(self.app.name) | |
# Initialize logging stuff, you can use app.config here | |
def log_response(self, flask_response): | |
# Can create/override logger stuff | |
pass | |
def __getattr__(self, name): | |
"""Forward any uncaught attributes to the instance object""" | |
logger = self.instance | |
if hasattr(logger, name): | |
return getattr(logger, name) | |
else: | |
raise AttributeError('%s has no attribute "%s"' % (self, name)) | |
class AltFlask(Flask): | |
"""Subclass of Flask to customize behavior. | |
This class is meant to be used in application factories. It modifies the | |
behavior of the following: | |
1) Routing. | |
2) Exception logging. | |
Subclassing Flask becomes necessary when an application grows, so it is | |
generally a good idea to do it from the start. | |
""" | |
@property | |
def logger(self): | |
"""Overrides the default logger property in Flask""" | |
if self._logger and self._logger.name == self.logger_name: | |
return self._logger | |
with _logger_lock: | |
if self._logger and self._logger.name == self.logger_name: | |
return self._logger | |
self._logger = rv = MyCustomLogger(self) | |
return rv |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This will initialize the logger on first use