Skip to content

Instantly share code, notes, and snippets.

@o3o3o
Created July 7, 2018 03:17
Show Gist options
  • Select an option

  • Save o3o3o/1faac4fe97a79d19f028a4248d2bfd7f to your computer and use it in GitHub Desktop.

Select an option

Save o3o3o/1faac4fe97a79d19f028a4248d2bfd7f to your computer and use it in GitHub Desktop.
log middleware
# duration: api 耗时,按秒计
# duration_ms: api 耗时,按毫秒计
# level: api 耗时档次,分为
# LEVEL-A: x < 1 sec
# LEVEL-B: 1 sec < x < 5 sec
# LEVEL-C: 5 sec < x < 10 sec
# LEVEL-D: x > 10 sec
# method: http 请求方法
# status_code: 请求响应状态
# user_agent: HTTP_USER_AGENT
DURATION_LOG_FORMATTER = ('{level} {x_forwarded_for} {user_agent} {method}'
' {path} {status_code} {duration}')
class DurationMiddleware(object):
def process_request(self, request):
request.duration_start = time.time()
def process_response(self, request, response):
duration = time.time() - request.duration_start
if duration < 1:
level = 'LEVEL-A'
elif duration < 5:
level = 'LEVEL-B'
elif duration < 10:
level = 'LEVEL-C'
else:
level = 'LEVEL-D'
info = {'x_user_real_ip': request.META.get('HTTP_X_USER_REAL_IP', '-'),
'remote_addr': request.META.get('REMOTE_ADDR', '-'),
'x_forwarded_for': request.META.get('HTTP_X_FORWARDED_FOR',
'-'),
'user_agent': request.META.get('HTTP_USER_AGENT', '-'),
'path': request.path.encode('utf8'),
'duration': str(decimal.Decimal(duration).quantize(
decimal.Decimal('0.001'))),
'duration_ms': str(decimal.Decimal(duration * 1000).quantize(
decimal.Decimal('1'))),
'level': level,
'method': request.method,
'status_code': getattr(response, 'status_code', '-')}
try:
msg = settings.DURATION_LOG_FORMATTER.format(**info)
if 'messenger' in request.path or level != 'LEVEL-A':
logging.info(msg)
except Exception:
logging.error(
'illegal format in settings.DURATION_LOG_FORMATTER, info: %s',
info, exc_info=True)
del request.duration_start
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment