Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
dmapi / usr / lib / python2.7 / dist-packages / dmapi / api / openstack / requestlog.py
Size: Mime:
# Copyright 2018 TrilioData Inc.
# All Rights Reserved.

"""Simple middleware for request logging."""

import time

from oslo_log import log as logging
from oslo_utils import excutils
import webob.dec
import webob.exc

from dmapi.api.openstack import wsgi
from dmapi import wsgi as base_wsgi

LOG = logging.getLogger(__name__)


class RequestLog(base_wsgi.Middleware):
    """WSGI Middleware to write a simple request log to.

    Borrowed from Paste Translogger
    """

    # This matches the placement fil
    _log_format = ('%(REMOTE_ADDR)s "%(REQUEST_METHOD)s %(REQUEST_URI)s" '
                   'status: %(status)s len: %(len)s '
                   'microversion: %(microversion)s time: %(time).6f')

    @staticmethod
    def _get_uri(environ):
        req_uri = (environ.get('SCRIPT_NAME', '') +
                   environ.get('PATH_INFO', ''))
        if environ.get('QUERY_STRING'):
            req_uri += '?' + environ['QUERY_STRING']
        return req_uri

    @staticmethod
    def _should_emit(req):
        """Conditions under which we should skip logging.

        If we detect we are running under eventlet wsgi processing, we
        already are logging things, let it go. This is broken out as a
        separate method so that it can be easily adjusted for testing.
        """
        if req.environ.get('eventlet.input', None) is not None:
            return False
        return True

    def _log_req(self, req, res, start):
        if not self._should_emit(req):
            return

        # in the event that things exploded really badly deeper in the
        # wsgi stack, res is going to be an empty dict for the
        # fallback logging. So never count on it having attributes.
        status = getattr(res, "status", "500 Error").split(None, 1)[0]
        data = {
            'REMOTE_ADDR': req.environ.get('REMOTE_ADDR', '-'),
            'REQUEST_METHOD': req.environ['REQUEST_METHOD'],
            'REQUEST_URI': self._get_uri(req.environ),
            'status': status,
            'len': getattr(res, "content_length", 0),
            'time': time.time() - start,
            'microversion': '-'
        }
        # set microversion if it exists
        if not req.api_version_request.is_null():
            data["microversion"] = req.api_version_request.get_string()
        LOG.info(self._log_format, data)

    @webob.dec.wsgify(RequestClass=wsgi.Request)
    def __call__(self, req):
        res = {}
        start = time.time()
        try:
            res = req.get_response(self.application)
            self._log_req(req, res, start)
            return res
        except Exception:
            with excutils.save_and_reraise_exception():
                self._log_req(req, res, start)