Ejemplo n.º 1
0
 def log_exception(self, exc_info):
     if not isinstance(exc_info, tuple):
         exc_info = sys.exc_info()
     if has_request_context():
         super(Frasco, self).log_exception(exc_info)
     else:
         self.logger.error('Exception [outside of request context]', exc_info=exc_info)
Ejemplo n.º 2
0
    def filter(self, record):
        if has_request_context() and callable(
                getattr(request, "get_extra_log_context", None)):
            for key, value in request.get_extra_log_context().items():
                setattr(record, key, value)

        return record
Ejemplo n.º 3
0
 def request_id(self):
     if has_request_context() and hasattr(request, 'request_id'):
         return request.request_id
     elif has_app_context() and 'request_id' in g:
         return g.request_id
     else:
         return 'no-request-id'
Ejemplo n.º 4
0
def msg_lang():
    if not has_request_context():
        raise LookupError("Can't determine message language when not currently in a request context.")
    lang = getattr(request, "lang", None)
    if lang is None:
        lang = request.accept_languages.best_match(_translations.keys(), default="en")
        request.lang = lang
    return lang
Ejemplo n.º 5
0
        def apply_async(self, args=None, kwargs=None, task_id=None, producer=None,
                        link=None, link_error=None, **options):
            kwargs = kwargs or {}

            if has_request_context() and hasattr(request, 'request_id'):
                kwargs['request_id'] = request.request_id

            return super().apply_async(args, kwargs, task_id, producer, link, link_error, **options)
    def send_task(self, name, args=None, kwargs=None, **other_kwargs):
        kwargs = kwargs or {}

        if has_request_context() and hasattr(request, 'request_id'):
            kwargs['request_id'] = request.request_id
        elif has_app_context() and 'request_id' in g:
            kwargs['request_id'] = g.request_id

        return super().send_task(name, args, kwargs, **other_kwargs)
        def apply_async(self, args=None, kwargs=None, **other_kwargs):
            kwargs = kwargs or {}

            if has_request_context() and hasattr(request, 'request_id'):
                kwargs['request_id'] = request.request_id
            elif has_app_context() and 'request_id' in g:
                kwargs['request_id'] = g.request_id

            return super().apply_async(args, kwargs, **other_kwargs)
Ejemplo n.º 8
0
        def apply_async(self, args=None, kwargs=None, task_id=None, producer=None,
                        link=None, link_error=None, **options):
            kwargs = kwargs or {}
            if has_request_context() and hasattr(request, 'request_id'):
                kwargs['request_id'] = request.request_id
            elif has_app_context() and 'request_id' in g:
                kwargs['request_id'] = g.request_id

            with SQS_APPLY_ASYNC_DURATION_SECONDS.labels(self.name).time():
                return super().apply_async(args, kwargs, task_id, producer, link, link_error, **options)
Ejemplo n.º 9
0
    def filter(self, log_record):
        """Provide some extra variables to be placed into the log message """

        # If we have an app context (because we're servicing an http request) then get the trace id we have
        # set in g (see app.py)
        if ctx.has_request_context():
            log_record.trace_id = g.trace_id
        else:
            log_record.trace_id = 'N/A'
        return True
Ejemplo n.º 10
0
        def after_cursor_execute(conn, cursor, statement, params, context,
                                 executemany):
            if app.debug and has_request_context():
                total_time = (time.time() -
                              conn.info['query_start_time'].pop(-1))
                with self._request_lock:
                    if hasattr(request, 'uuid') and (request.uuid
                                                     in self._request_info):

                        if executemany:
                            for param in params:
                                _request_info_queries(statement, param,
                                                      total_time)
                        else:
                            _request_info_queries(statement, params,
                                                  total_time)
Ejemplo n.º 11
0
def get_flask_request_id():
    """Return the request ID from the Flask request context

    If there is a Flask request context but there is no ``request_id``
    then first we look for a ``TS-Request-ID`` header. If that is also
    not there we generate a new string uuid4.

    Importing this module will register this getter with ``get_request_id``.

    Returns:
        str: the current request ID
    """
    if has_request_context():
        if 'request_id' not in g:
            g.request_id = request.headers.get('TS-Request-ID',
                                               str(uuid.uuid4()))
        return g.request_id
Ejemplo n.º 12
0
def get_flask_request_id():
    """Return the request ID from the Flask request context

    If there is a Flask request context but there is no ``request_id``
    then first we look for a ``TS-Request-ID`` header. If that is also
    not there we generate a new string uuid4.

    Importing this module will register this getter with ``get_request_id``.

    Returns:
        str: the current request ID
    """
    if has_request_context():
        if TS_REQUEST_ID in request.headers:
            return request.headers[TS_REQUEST_ID]

        if 'request_id' in g:
            return g.request_id

    return None
Ejemplo n.º 13
0
def _handle_exception(_exception: Exception) -> None:
    # Flask's documentation is confusing, and this presents a good example of why stackoverflow
    # should *not* be trusted. Users on stackoverflow claim that request context is not available
    # during teardown_request, but this is not true. teardown_request is called immediately before
    # the request context stack is popped, not after. Thus, we have access to the request and
    # can log information about it. To be absolutely safe, I call has_request_context. Really
    # is not necessary unless Flask makes a breaking change to their framework.

    # Sanity check. Should not happen, but I have seen multiple apps include this check, which
    # suggests that maybe it could happen in some crazy circumstance.
    if not _exception:
        return

    # Another sanity check. Should never happen.
    if not has_request_context():
        return

    # Note that we do not have access to the response object (it may not even exist),
    # so we cannot record everything. That is okay, as for unhandled exceptions all we want to know
    # is what was called.

    _log_request()
Ejemplo n.º 14
0
def _get_current_context():
    if has_request_context():
        return request

    if current_app:
        return current_app
Ejemplo n.º 15
0
def _get_user():
    if has_request_context() and not hasattr(_request_ctx_stack.top, 'user'):
        current_app.login_manager._load_user()

    return getattr(_request_ctx_stack.top, 'user', None)
Ejemplo n.º 16
0
 def enabled_for_record(self, record):
     return record.levelno >= logging.WARNING or (
         has_request_context() and getattr(request, "is_sampled", False))
Ejemplo n.º 17
0
def _get_translations():
    if has_request_context() and request.form.get('use-translation') == 'oc':
        babel_ext = flask_babel.current_app.extensions['babel']
        return Translations.load(next(babel_ext.translation_directories), 'oc')

    return _flask_babel_get_translations()
Ejemplo n.º 18
0
def localized_of(variants: dict):
    if not has_request_context():
        raise LookupError("Can't select a localized variant when we're not currently in a request context.")
    lang = request.accept_languages.best_match(variants.keys(), default="")
    return variants[lang]
Ejemplo n.º 19
0
 def request_id(self):
     if not has_request_context():
         return 'no-request-id'
     else:
         return request.request_id
Ejemplo n.º 20
0
def _get_translations():
    if has_request_context() and request.form.get("use-translation") == "oc":
        babel_ext = flask_babel.current_app.extensions["babel"]
        return Translations.load(next(babel_ext.translation_directories), "oc")

    return _flask_babel_get_translations()
Ejemplo n.º 21
0
 def request_id(self):
     if has_request_context() and hasattr(request, 'request_id'):
         return request.request_id
     else:
         return 'no-request-id'
def request_is_sampled(log_context):
    """A public condition that returns True if the request has the X-B3-Sampled flag set in its headers. While this is
    the default condition for logged_duration, exposing it publically allows it to be easily combined with other
    conditions."""
    return has_request_context() and getattr(request, "is_sampled", False)
def request_context_and_any_of_slow_call_or_sampled_request_or_exception_in_stack(
        log_context):
    return has_request_context() and (
        exceeds_slow_external_call_threshold(log_context)
        or request_is_sampled(log_context) or exception_in_stack())
Ejemplo n.º 24
0
def _get_current_context():
    if has_request_context():
        return request

    if current_app:
        return current_app
def _logged_duration_default_condition(log_context):
    return has_request_context() and (
        getattr(request, "is_sampled", False)
        or log_context.get("duration_real", 0) > SLOW_DEFAULT_CALL_THRESHOLD)