Last active
October 17, 2015 01:14
-
-
Save philfreo/a96b29183f22c5e55446 to your computer and use it in GitHub Desktop.
Python/Flask+Rollbar as logger handler + structlog support
This file contains 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
class StructlogRollbarHandler(RollbarHandler): | |
def __init__(self, prefix, *args, **kwargs): | |
self.prefix = prefix | |
super(StructlogRollbarHandler, self).__init__(*args, **kwargs) | |
def format_title(self, data): | |
# Keys used to construct the title and for grouping purposes. | |
KEYS = ['event', 'func', 'exception_name', 'queue'] | |
def format_field(field, value): | |
if field == 'queue': | |
return '%s=%s' % (field, value.split('.')[0]) | |
else: | |
return '%s=%s' % (field, value) | |
return '%s: %s' % (self.prefix, ' '.join(format_field(key, data[key]) for key in KEYS if key in data)) | |
def emit(self, record): | |
level = record.levelname.lower() | |
if level not in self.SUPPORTED_LEVELS: | |
return | |
if record.levelno < self.notify_level: | |
return | |
data = json.loads(record.msg) | |
# Title and grouping | |
data['title'] = data['fingerprint'] = self.format_title(data) | |
uuid = rollbar.report_message( | |
message=data.pop('traceback', data['title']), | |
level=level, | |
request=rollbar.get_request(), | |
extra_data={}, | |
payload_data=data, | |
) | |
if uuid: | |
record.rollbar_uuid = uuid | |
def enable_rollbar(logger, handler=RollbarHandler, level=logging.ERROR): | |
# Send errors to Rollbar.com | |
# https://github.com/rollbar/pyrollbar/blob/master/rollbar/logger.py | |
from closeio.main import app | |
if app.debug: | |
return | |
rollbar.init(app.config['ROLLBAR_API_KEY'], | |
app.config['APPLICATION_ENVIRONMENT'], | |
allow_logging_basic_config=False) | |
if inspect.isclass(handler): | |
handler = handler() | |
rollbar_handler = handler | |
rollbar_handler.setLevel(level) | |
logger.addHandler(rollbar_handler) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment