From 6b49af4fb7fe73ce8c2cd634ba2b3196360ad37e Mon Sep 17 00:00:00 2001 From: TheAMM Date: Sat, 2 Sep 2017 22:16:28 +0300 Subject: [PATCH] Exception handling: include a random string to identify stacks from log --- nyaa/__init__.py | 15 ++++++++++++--- nyaa/utils.py | 8 ++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/nyaa/__init__.py b/nyaa/__init__.py index 0fb406e..f2d33fc 100644 --- a/nyaa/__init__.py +++ b/nyaa/__init__.py @@ -1,5 +1,6 @@ import logging import os +import string import flask from flask_assets import Bundle # noqa F401 @@ -7,6 +8,7 @@ from flask_assets import Bundle # noqa F401 from nyaa.api_handler import api_blueprint from nyaa.extensions import assets, db, fix_paginate, toolbar from nyaa.template_utils import bp as template_utils_bp +from nyaa.utils import random_string from nyaa.views import register_views @@ -46,9 +48,16 @@ def create_app(config): if not app.config['DEBUG']: @app.errorhandler(500) def internal_error(exception): - app.logger.error(exception) - flask.flash(flask.Markup( - 'An error occurred! Debug information has been logged.'), 'danger') + random_id = random_string(8, string.ascii_uppercase + string.digits) + # Pst. Not actually unique, but don't tell anyone! + app.logger.error('Exception occurred! Unique ID: %s', random_id, exc_info=exception) + markup_source = ' '.join([ + 'An error occurred!', + 'Debug information has been logged.', + 'Please pass along this ID: {}'.format(random_id) + ]) + + flask.flash(flask.Markup(markup_source), 'danger') return flask.redirect(flask.url_for('main.home')) # Get git commit hash diff --git a/nyaa/utils.py b/nyaa/utils.py index 2077837..c07f213 100644 --- a/nyaa/utils.py +++ b/nyaa/utils.py @@ -1,5 +1,7 @@ import functools import hashlib +import random +import string from collections import OrderedDict @@ -22,6 +24,12 @@ def sorted_pathdict(input_dict): return OrderedDict(sorted(directories.items()) + sorted(files.items())) +def random_string(length, charset=None): + if charset is None: + charset = string.ascii_letters + string.digits + return ''.join(random.choice(charset) for i in range(length)) + + def cached_function(f): sentinel = object() f._cached_value = sentinel