Skip to content

Instantly share code, notes, and snippets.

@reallistic
Created February 27, 2017 17:41
Show Gist options
  • Select an option

  • Save reallistic/f094b9e4205c413aa93f5e4fbd96017e to your computer and use it in GitHub Desktop.

Select an option

Save reallistic/f094b9e4205c413aa93f5e4fbd96017e to your computer and use it in GitHub Desktop.
Example logging setup with python flask
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
@reallistic
Copy link
Copy Markdown
Author

This will initialize the logger on first use

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