Statistics logging for Django

brad's picture

Last night I built some middleware/models for a django application to log visitor/user activity on the site. The intention is to be able to do better user tracking, and build more comprehensive statistics stored in the mysql db (obviously I am also logging everything with apache). The current set up still needs some periodical scripts to conflate data into statistics. I was thinking of doing a daily-weekly-monthly routine (i.e. once a day stats are conflated for yesterday's stats, and once a week they are turned into weekly stats, and once a month they are minimised into a monthly overview. It was actually really simple to implement, but I butted my head against some django issues (more at the end).

So, first we build a model to represent a request:


class UserActivity(models.Model):
        user = models.ForeignKey(
                      User,
                      null=True, blank=True,
                      db_index=True
               )
        session = models.ForeignKey(
                      Session,
                      db_index=True,
                      null=True, blank=True
                  )
        date = models.DateTimeField(
                      help_text="Date Request started processing",
                      auto_now_add=True,
                      db_index=True)
        request_time = models.IntegerField(
                              help_text="Processing time (in ms)",
                              null=True, blank=True)
        request_url = models.CharField(maxlength=800,db_index=True)
        referer_url = models.URLField(
                              verify_exists=False,
                              db_index=True,
                              blank=True, null=True)
        client_address = models.IPAddressField(
                              blank=True,null=True)
        client_host = models.CharField(
                              maxlength=256,
                              blank=True,null=True)
        browser_info = models.TextField(null=True,blank=True)
        error = models.TextField(null=True,blank=True)
        def set_request_time(self):
                from datetime import datetime
                self.request_time = (
                                      datetime.now() - 
                                      self.date 
                                    ).microseconds
                self.save()

(download models.py_.txt)

I think the model captures all the relevant info (we tie a request to a session and user, we have the time they made the request (and using middleware we can calculate how long the request took), the referer, and some info about the client).

Most of the fields can be blank/null because we are not always going to have a session (see below), etc.

The function set_request_time is called by the outgoing middleware function (process_response) and just notes how long the request took, and saves the object.

Next we need some middleware to handle the object creation:


from datetime import datetime
from django.conf import settings
from my_app.models import UserActivity

class Activity(object):
        def process_request(self,request):
                if request.META.has_key('HTTP_REFERER'):
                        referer = request.META['HTTP_REFERER']
                else:
                        referer = ''

                self.activity = UserActivity(
                        user = request.user,
                        session = request.session,
                        date = datetime.now(),
                        request_url = request.META['PATH_INFO'],
                        referer_url = referer,
                        client_address = request.META['REMOTE_ADDR'],
                        client_host = request.META['REMOTE_HOST'],
                        browser_info = request.META['HTTP_USER_AGENT']
                )

        def process_exception(self,request,exception):
                self.activity.error = exception
                self.activity.save()

        def process_response(self,request,response):
                self.activity.set_request_time()
                return response

(download middleware.py_.txt)

You may (or may not) have noticed that we only actually save our model on the outgoing response, so we only have one db write per request. The middleware system is very easy to build for, and is documented here. The nice thing is the process_exception will keep a record of the exception (but I am not sure if this could be done so it stores more information than just the exception.__str__()?)

To install this you would need to have your model within in an app that is "installed" and "syncdb". The middleware needs to be placed after the session middleware, for e.g. in settings.py (in MIDDLEWARE_CLASSES):

    
    "django.middleware.common.CommonMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "league.middleware.Activity",

The next step is to build a context_processor that will include some useful stats like who is logged in etc. but that will need a more models, or mysql view or UserActivityManager that does a custom sql request with some "group by" magic. I have not built those parts yet, so I won't speak about them yet.

My gripes about this implementation doing regular user activity stats is a relatively costly request (you need to do a SELECT COUNT(*) WHERE date>now()-(20 minutes) GROUP BY user). This could be cheapened by having a OneToOne join table with the user table which just has an indexed recent_activity field against a User which is touched every request from that user. To get anonymous user activity we can only really rely on ip addresses, since sessions are not set until a user logs in/logs out, so we would need to do a similar system to the user OneToOne table, and use the REPLACE syntax of mysql (not sure if this is possible using django).

My gripes about the session middleware is that users do not get sessions until they log in/log out. This is good because once of visitor etc. do not get sent a cookie, and you don't allocate them a session in the DB, but it means unique sessions are more difficult to track because anonymous, first time visitors are only unique by their IP address, and nothing else. I can obviously change this, by setting any session variable for visitors without a session in the process_request of the activity middleware. This is neat because it is an opt in db hit, but after wrestling for ages with session middleware appreciating opt in is something to be done in the sober light of day.

My gripes about Django's ORM are that there is no neat way to do custom sql requests (the nicest group by sql snippet I have seen is this one because it uses django's _meta to get the table names). Newer changes in Django introduced the extra parameter, which means less completely custom sql (i.e. you can just append your customisations to the existing sql statement), but it still doesn't allow you to use very specific stuff like GROUP BY (which not all DBs support). The way to remedy this is to figure out some way you can still send sanitised sql to a db server in an extra statement, while allowing more appended customisations for developers. The alternative is to build group_by functions which either translate to DB specific requests, or do it virtually (much like the transactions infrastructure). I prefer the latter solution because I think GROUP BY is very relevant and very useful, but the latter solution does mean that if your DB doesnt support it, then it could be a very costly operation in python-space.

AttachmentSize
middleware.py_.txt825 bytes
models.py_.txt1.17 KB

Trackback URL for this post:

http://whijo.net/trackback/108

Brad,

I think you'll be able to do what you want using a custom manager within your Django model.

Al.

Thanks for the tip Al. Your tip worked perfectly for me.

this definitely help in user tracking. I have tried this at work and it worked well. thanks for the great info
bdhost

As a professional IT study materials provider, Pass4sure is specially designed for IT candidates who want to pass any IT exams, supported by a powerful team for product research and development, as well as website development and operation. Its vendors like Cisco, Microsoft, IBM, Sun, compTIA, HP, etc, are all positioned as leaders in the IT field.The Most Popular Vendors List :
HP exam Oracle exam Oracle certification Cisco certification
The Most Popular Certifications List :
NCSE exam NCTS certification CCDP exam CCDP exam SCJP certification JNCIA certification IBM DB2 certification CCIP exam SCJP certification CCDP certification CCVP exam CCIE exam
The Most Popular exams List :
350-050 642-436 HP0-S21 646-363 156-315.65 VCP-310 350-001 CISSP SK0-002 JK0-016 1Z0-051 CISSP JN0-331 646-363 642-524
650-180 220-702 642-892 642-681 220-602 640-816
Click Pass4sure to get more information!

A free sex video of sweet natural hairy Swamy Nithyananda’ having sex with a top tamil actress and other nude girls was broadcast on TV live and has shocked people across India. Naked girls were typed on video by anonumous author. Since a Swamy is supposed to be a spiritual person- this revelation has followers questioning hairy bush Nithyananda's faith. Originally this xxx video was posted on youtube but then moved to other sex tube portals.
ABB728019384 порно видео

dude as alway great post.

Paris hotels

Trailing behind common wisdom, the django logging statistics have done it again. Their penchant for the notorious sainsburys voucher codes means that few will now go further. It's up to the consumer now.

The hair designs are very great in this software and this is best used in the saloons for the easier demonstration.
Regards,
salon software

h, executive bvlgari bvlgari director of ACLU Nebraska, with links jewellery the license required by a gucci man jewelry renter for every move becoming dior watches a handy tracking mechanism.
Attorney Kris replica Couple Jewelry Kobach, who helped draft the zenith replica Fremont ordinance and has helped jaeger le coultre replica write and defend similar measures cartier love bracelet price around the country as well knock off jewelry as the Arizona state law, replica jewellery is confident the ordinance will oris replica

This post is doing weird things to my submission. It makes me go to other pages. Anybody know what might be causing this? I'm trying to show people my black trolley suitcase and favorite whistling kettle. These guys make it hard.

The subject of this article is really interesting, nice to see the clear presentation here. Keep up the good work. Thanks for sharing this useful information.
Live Streaming Boxing PPV Online
Demand PPV Boxing
Hbo Ppv Live Stream
Watch live online streaming Boxing PPV
boxing live streaming in demand

Ich habe das gerade mal auf meiner Seite versucht - es handelt sich hierbei um eine Liste für Singlebörsen. Alles in allen hat das super geklappt. Wobei ich sagen muss, das es auf anderen Seiten nicht so dolle Funktioniert hat. Bei diesen Seiten ging es vorwiegend um Erotik und natürlich auch um den ein oder anderen geilen Porno. Naja egal und wie auch immer - ich danke dir...

uggs outletStores sell all kinds of uggs boots,come our UGG Boots Outlet stores get ugg classic boots,ugg bailey button boots with free shipping.In the ugg outlet, you can find different types of UGG boots with different colors and different sizes. We have tons of sale shoes, womens sale shoes, keen sale, ugg sale, discount uggs.

Traditionally the [url=http://www.24replicawatches.com/replica-michele-watches.html]Replica Michele Watches[/url] local furniture [url=http://www.24replicawatches.com/]replica watches[/url] store [url=http://www.replicawatcheshk.com/replica-Concord-watches.html]fake Concord Watches[/url] would buy wholesale furniture from [url=http://www.24replicawatches.com/]replica watches[/url] independent sales reps that became trusted resources [url=http://www.replicawatcheshk.com/replica-Oris-watches.html][/url] for [url=http://www.my-luxury-watches.com/replica-rado-watches.html]fake Rado Watches[/url] new designs, catalogs [url=http://www.24designerreplica.com/replica-Christian-Dior.html]Replica Christian Dior[/url] and [url=http://www.replicabagsbuy.com/Christian-Dior-handbags-replica.html][/url] wholesale companies that might [url=http://www.replica-aaa-handbags.com/Louis-Vuitton-handbags-replica.html]replica louis vuitton handbags[/url] not [url=http://www.replicawatcheshk.com/]replica watches[/url] ever market into [url=http://www.24replicawatches.com/replica-zenith-watches.html]fake Zenith Watches[/url] a [url=http://www.replicawatcheshk.com/replica-Oris-watches.html]replica Oris watches[/url] territory due to [url=http://www.replicawatcheshk.com/replica-Vacheron-Constantin-watches.html]Replica Vacheron Constantin[/url] cost. [url=http://www.replicabagsbuy.com/]designer handbags[/url] Territories, which ranged [url=http://www.replicabagsbuy.com/Giverchy-handbags-replica.html]Replica Giverchy [/url] from [url=http://www.24replicawatches.com/]replica Breitling[/url] some [url=http://www.replicawatchcn.com/]replica watches[/url] zip codes [url=http://www.replicabagsbuy.com/Marc-Jacobs-handbags-replica.html]Replica Marc Jacobs [/url] to several [url=http://www.24replicawatches.com/replica-breitling-watches.html][/url] states, could [url=http://www.24designerreplica.com/replica-Tissot.html]replica Tissot[/url] cost [url=http://www.replicawatcheshk.com/replica-TAG-Heuer-watches.html]replica TAG Heuer watches[/url] a furniture wholesale company several hundreds of thousands of [url=http://www.my-luxury-watches.com/replica-rado-watches.html]Replica Rado Watches[/url] dollars to staff [url=http://www.replicabagsbuy.com/Hermes-handbags-replica.html]replica hermes handbags[/url] resourcefully from the company [url=http://www.24replicawatches.com/replica-raymond-weil-watches.html]replica Raymond Weil[/url] support, [url=http://www.24replicawatches.com/replica-vacheron-constantin-watches.html]Replica Vacheron Constantin[/url] catalog making, travel [url=http://www.watchesetrade.com/]china replica watches[/url] fees [url=http://www.replicawatcheshk.com/replica-Rado-watches.html]fake Rado Watches[/url] such as gas and [url=http://www.replicawatcheshk.com/replica-Gucci-watches.html]Replica Gucci Watches[/url] hotels and telecommunication costs. [url=http://www.replicawatcheshk.com/replica-Oris-watches.html][/url] Since the consumer has demanded lower and lower costs for the finished furniture [url=http://www.replicabagsbuy.com/Marc-Jacobs-handbags-replica.html]Replica Marc Jacobs handbags[/url] product and the [url=http://www.my-luxury-watches.com/replica-a-lange-and-sohne-watches.html]Replica A Lange Sohne[/url] current sales volume has dried [url=http://www.replica-aaa-handbags.com/Gucci-handbags-replica.html]replica gucci handbags[/url] [url=http://www.24designerreplica.com/replica-Zenith.html]Replica Zenith Watches[/url] up due to the recession, [url=http://www.my-luxury-watches.com/replica-omega-watches.html]replica Omega watches[/url] sometimes the sales [url=http://www.replicabagsbuy.com/Loewe-handbags-replica.html][/url] reps have been cut out [url=http://www.replicawatcheshk.com/replica-Omega-watches.html]replica Omega watches[/url] entirely and replaced with an online ordering system.

In order to push costs down to as low as possible, many [url=http://www.24replicawatches.com/replica-ebel-watches.html]Replica Ebel[/url] wholesale companies [url=http://www.24replicawatches.com/replica-cartier-watches.html]replica Cartier[/url] started [url=http://www.my-luxury-watches.com/replica-breitling-watches.html]replica Breitling watches[/url] to rest their inventory [url=http://www.my-luxury-watches.com/replica-jaeger-le-coultre-watches.html]replica Jaeger Le Coultre watches[/url] [url=http://www.replicafakewatch.com/]fake watches[/url] online to make it easier [url=http://www.24replicawatches.com/replica-rolex-watches.html][/url] [url=http://www.24replicawatches.com/]replica watch[/url] for the retailer to purchase items instantly from their company. The [url=http://www.24replicawatches.com/]fake watches[/url] advantage to [url=http://www.watchesetrade.com/]fake watches[/url] the retailer is they now have instant access to how many [url=http://www.24designerreplica.com/replica-Tissot.html]fake Tissot Watches[/url] items are offered from the wholesaler. Not that many years ago, the retailer used to have to call in to see [url=http://www.replicawatcheshk.com/replica-Chanel-watches.html]replica Chanel watches[/url] if [url=http://www.buy-cheap-clothes.com/]cheap clothes[/url] the furniture wholesaler had [url=http://www.my-luxury-watches.com/replica-tag-heuer-watches.html]Replica Tag Heuer Watches[/url] an [url=http://www.24replicawatches.com/replica-patek-philippe-watches.html]Replica Patek Philippe[/url] item in s

Children book Replica Panerai packs have surely fake watches come a long way, as earlier generations had to carry uncomfortable and unsightly replica Tag Heuer watches bags around. You might be thinking that today s children Replica Bally handbags spoilt with their stylish Replica Hermes handbags and expensive book fake watches packs, but this is not really replica Patek Philippe the case. It fake Loewe handbags Replica Patek Philippe Watches is no wonder that the cases of stress and back problems are increasing Replica Yves Saint Laurent handbags with the increasing workload that today s children Replica Prada are facing. Children feel stressed due to insane after school activity schedules, heavier replica Tag Heuer watches workloads, and the constant pressure to perform. There is no doubt it that today s school children are subject to more pressure than older generations.

So fake Tag Heuer Watches what can you replica chenel handbags do to make your replica Zenith children s replica Jaeger Le Coultre life a replica handbags bit easier? replica gucci handbags You can initiate by choosing the right school Replica Juicy Couture bag replica Zenith for them. Why add exhaustion, backache, and Replica Omega Watches strained Replica Vacheron Constantin muscles to their Replica Breitling long list of problems and stresses? The American Occupational Therapy Association advises children replica Omega not to carry any school bag that weighs 15 percent more of their body weight. fake Yves Saint Laurent handbags Anything more equals replica handbags that replica Piaget watches they are placing a heavy replica Omega watches and dangerous fake Omega Watches load fake Chloe handbags on replica watch their backs. Modern Children s book packs Replica Chanel are the replica Tissot safest choice for replica omega your replica louis vuitton child, and now a fake watches day, a number of models available come wi

What an amazing blog. I have found this blog very interesting because I have gotten the most read information. This blog help me out otherwise I don’t know how much time I have to spend for getting right information.
Regards,
cheap auto insurance

Great blog always offer the best and authentic information without creating exaggeration. This blog has given me opportunity to learn many things regarding products and services.
Regards,
sex toys

Indeed there are several development going on like Tenant screening services in the country. And the commenter feels good that he is given the chace to exress himself about this marvelous piecve. Truly commendable! I need to see more.

This is really a very interesting post. It really peaks my interest to read your article further. Very significant article for us, I think the representation of this article is actually superb one. This is my first visit to your site. Keep blogging and thanks for sharing.
Regards,
michigan car insurance

Excellent news. Droid 2 and Twilight Bedding and LED vs LCD

I truly enjoyed reading your weblog Mercedes-Benz Mobil Mewah Terbaik Indonesia and points that you expressed.

Versions of Django prior to 1.0 had multithreading issues and it would be recommended that those versions of Django only be used in a single threaded server configuration, such as with Apache prefork MPM using mod_python or embedded mode of mod_wsgi. Thanks a lot.
Regards,
online dating site

This is a smart blog. I mean it. You have so much knowledge about this issue, and so much passion. You also know how to make people rally behind it, obviously from the responses. Youve got a design here thats not too flashy, but makes a statement as big as what youre saying. Great job, indeed. Turquoise Color Katy Perry perfume Madonna Truth or Dare Curly Hairstyles Celebrity Boots Justine Bieber Hairstyles Katy Perry Blue Hair Beanie Hats Fishtail Braid Denim Dresses

Technology is evolving overtime. People are very dependent in technology to make life easier. That is why inventors invent things that could give convenience to people.
Hawaiian Holidays | Caribbean Vacation
alexander vs bradley | Business Continuity Disaster recovery

I am very much pleased with the contents you have mentioned.I wanted to thank you for this great article. I enjoyed every little bit part of it and I will be waiting for the new updates.

Fraxel laser

I have read stuff from. Thank you for posting when you have the opportunity, Guess I’ll just book mark this blog... Cell Phone Spy Software

I have done IT job also and we can have some new information about this field,some new sites will help for getting the help for details ,so I have so many sites like this, please visit the link here for getting those details,

Thanks and regards:

osteopathbrighton

Content comparable Public Holidays to this help make this weblog. Site really worth coming Submit Article again to for even far more details. Obviously especially Montenegro Hotel excellent content right here.

fanbullet.com will give a boost to your website traffic. Facebook provides a great platform to spread the awareness of the business to get the target audience in all possible categories. I buy some 4000 of Facebook fans from fanbullet.com and experience an awesome response. This help me from time to time and my business reaches to the new heights. Thanks Fanbullet.

facebook marketing

Nice site! I enjoy a couple of from the articles which have been written, and particularly the comments posted!
Housefull 2 Songs , Agent Vinod Songs , Blood Money Songs , Jodi Breakers songs , Jannat 2 Songs , Chaar Din Ki Chandni Songs , Bittoo Boss Songs

nike norge as Nike Free Run ds, and 26 miles per nike shox norge gallon nike free 3.0 for highways.

Generosity is Nike Free a Nike Shox nike free 2.0 trait Nike Free Norge that the 2006 Mazda6 has. You Nike Shox nike sko can find Nike Oslo features Nike Free Run 2.0 like air nike nettbutikk conditioning, power... Nike Free Run Norge

It previously was a very terrifying situation Tablet Android Honeycomb Terbaik Murah in my view, nevertheless taking note of a new well-written style you treated it took me to cry over fulfillment.

Hm there seems to be a problem loading the images on your site, I don't know what it is but it looks kind of strange right now. Like, text only. Maybe it's just temporary I don't know, but you might want to check it out...

I definitely loved 2011 Easter every little bit of it. This is very nice one and gives Easter 2011 indepth information. This is really a Easter tremendous site.

This article is very interesting, I like it. I will always come to visit after.I would recommend to friends more.

I have read this post and if Gogo2011 Kobamusaji I could I want to suggest you few interesting things or advice.

I found so many interesting stuff Harga Jual Blackberry iPhone Laptop Murah in your blog, especially its discussion.

Post new comment

The content of this field is kept private and will not be shown publicly.
Captcha
This question is used to make sure you are a human visitor and to prevent spam submissions.
Syndicate content

Recent comments

About this website

Whijo.net is the online internets of Bradley Whittington, Amanda Joseph, and our son Finley James Whittington. "Whijo" is 29% Whittington, 33% Joseph, and 37% Internet. Quite Web 2.0 of us.