Server Access Logging in Django using middleware

Some application admins need to know which user performed what action in the application. We also felt the need of such tracking hence we started developing the access log system for our application.

In this article we will see how to develop the server access logging app for Django project.

We will be storing below information:

  • URL/link visited.
  • Request method, get or post.
  • Get or Post Data
  • Referrer
  • IP address of visitor
  • Session ID

What is access log:

An access log is a list of all the requests for individual files that website visitors have requested from the website.

Why access log:

We can analyse the access logs and figure out multiple aspects of website visitors and their behaviour:

  • Origin of request i.e. referrer
  • Location of visitor
  • What page or link is visited most
  • In case of audit, which visitor clicked on which page and searched what. etc.

Access Logs:

To start access logging, we will be using middleware. Create a Django project and create an app in project. We strongly recommend to use virtual environment for python or Django project development.

To log the information, we need to create model.

Model:

Create a model in your app’s models.py file.

Middleware:

Now create a file logging_middleware.py  in your app.

In the file above, we are doing following things:

  1. Since we are using session key to uniquely identifying the request, we need to create session if session key doesn’t exists.
  2. Get the path i.e. URL which user/visitor visited.
  3. Collect, IP address, request method, referrer URL and session key.
  4. Collect the post and get data and remove the sensitive information like password. You may edit the logic as per your requirement.
  5. Store the data with timestamp in table.
Settings:

For the above code to work, we need to complete below settings:

  • Add your app in installed app’s list in settings.py file.
  • Add your middleware class in middleware classes list.
  • Make migrations to create the Model table in database.

Now start hitting the application URLs and you can see the entry in your table.

server access logs in django

 

Complete code is available on Github.

Future Work:

You may make changes in middleware code to

  • Ignore hits on static and media URL.
  • Log user_id if user is logged in.
Data Cleanup:

Since access_log  table will take a lot of space, it is good idea to delete the old entries. You might want to create a management command and schedule it to delete the data periodically.

create a command and use below code for cleanup.

 

 

Must read article for middleware : How to develop a distributable Django app to block the crawling IP addresses

 

(Visited 321 times, 1 visits today)

You must read this :

2 thoughts on “Server Access Logging in Django using middleware”

Leave a Reply

Your email address will not be published. Required fields are marked *