Sample custom access logging module implemented by Django

  • 2020-06-07 04:46:16
  • OfStack

This article is an example of a custom access logging module implemented by Django. To share for your reference, specific as follows:

There is no access logging module in Django by default, but we can implement one of our own through Middleware of Django.

First, create an ES10en. py file under the Django project with the following contents:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
class AccessMiddleware(object):
  def process_request(self, request):
    meta = request.META
    print "[%s] PATH_INFO=%s, REMOTE_ADDR=%s, HTTP_USER_AGENT=%s" \
       %(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
        meta['PATH_INFO'], meta['REMOTE_ADDR'], meta['HTTP_USER_AGENT'])
    return None
  def process_response(self, request, response):
    return response

Where process_request() should return an None or HttpResponse object.

If None is returned, Django continues to process the request, executes the subsequent middleware, and then invokes the corresponding view.

If an HttpResponse object is returned, Django will not execute any other middleware of any kind and the corresponding ES29en.Django will immediately return this HttpResponse.

Then modify the file and add the AccessMiddleware created above in the MIDDLEWARE_CLASSES section, such as :(see last line 1)


Restart the service and visit any page to see the log output.

For more information about Python, please refer to: Summary of Python Logging skills, Python Data Structure and Algorithm Tutorial, Python Function Skills Summary, Python String Skills Summary and Python Introductory and Advanced Classic Tutorial.

I hope this article has been helpful in Python programming.

Related articles: