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.

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

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

Life insurance or life assurance is a contract between the policy owner and the insurer, where the insurer agrees to pay a designated beneficiary a sum of money upon the occurrence of the insured individual's or individuals' death or other event
Regards,
online health insurance quotes

Corporate video production covers a wide range of purposes from corporate communication, training and education, videotaping conferences and conventions, and sales.
Regards,
corporate video production

Comparability and replica Longines watches distinction essay is Replica A.Lange Sohne without fake handbags doubt one of fake Jaeger Le Coultre Watches the replica Breitling watches commonest assignments in American replica Rado watches excessive colleges and Replica TAG Heuer Watches universities. designer handbags In the sort fake Balenciaga handbags of replica watches an essay the Replica Versace scholars have to compare two (in some essays replica Jaeger LeCoultre watches a number of) issues, problems, occasions or ideas- replica watches replica tag heuer and consider their resemblances and differences. This type of an essay advances and develops your crucial replica Piaget watches considering in addition to an essay your argumentation and understanding of the importance of the Replica IWC Watches occasions fake Marni handbags and issues that you simply compare.
There s an instance of Replica Loewe the headings of among the compare/contrast assignments.
Compare and fake TAG Heuer Watches contrast the weather situations for the growing of the cotton between Texas and California.
Examine fake watches the strategy to the Soviet Union of F.D. Roosevelt and H. Truman. Replica Tissot What are the cheap clothing similarities/the variations of their Replica Cartier coverage?
Compare and the essays contrast the flicks God Replica Thomas Wylde handbags Farther replica louis vuitton and Once fake A. Lange and Sohne Watches upon a time inAmerica. />
Generally, fake chanel chances replica watches are you ll be asked to check, replica Jaeger Le Coultre sometimes you may be replica IWC watches requested to contrast, and on a number of events Replica Omega each actions mentioned ought to be performed.
But, on the similar fake Jaeger Le Coultre Watches time comparison/contrast might replica IWC watches be a part of nike shoes some essay as w

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.

earth4energy save fuel Electronic Cigarette grow taller error fix

Great tutorial I'm going toput it into action on my how to make money online and debt solutions sites, I'll let you know how I get on. I'll link to this posy from, grooms speech, puppy toilet training , piano tutorial, how to fight and online spanish classes as I think its worth the link juice.

I am quite impressed and just wanted to let you know that you did a fine job on this article. However, I do have some unanswered questions that I would like to ask you. I will contact you via email so that you can clear some of these things up for me. Again, very well written article. Keep up the good work. Acne Scars
Cho Yung Tea Watch Vampires Suck Online

I am happy to find this post very useful for me, thanks for sharing it here.
Tom Ford Sunglasses

I like the foundation of this blog has a great variety of comments I really like it, several cash gifting points of view helps in the appreciation of the forex trading system subject,is very interesting and I would like learn more.

zadoc

Bow ties may be made of any fabric material, but most are made from silk, polyester, cotton or a mixture of fabrics. Some fabrics like wool are much less common for bow ties than for ordinary four-in-hand neckties. The bow tie originated among Croatian mercenaries during the Prussian wars of the 17th century. The Croats used a scarf around the neck to hold together the opening of their shirts. This was soon adopted under the name cravat, derived from the French for Croat by the upper classes in France, then a leader in fashion and flourished in the 18th and 19th centuries.

Very cool thoughts! gay webcam dating

Rest Replica Tissot room wall mirrors replica Tag Heuer are fake Oris Watches one other home item fake Casio Watches that has modified shoe store from being Replica Oris Watches a purely utilitarian personal grooming tool into replica watches a Replica Miu Miu Replica Gucci excessive style addition to Replica Panerai your replica louis vuitton lavatory design ideas. I fake chanel ve chosen a collection of among the latest fashion replica chenel handbags traits to Replica Cartier Watches

dress up games for girls and begin working to give your doll a new look.
You can style the doll with different dress up games to your styling sense.
Rs2guru wedding invitations Department is specialized in wedding
invitation designing wedding invitations
and wedding invitation wording printing, and we provide High quality and reasonable price to you.
On our site you can see a wide range of personalized Wedding Invitations. We strive to offer you the best choice of
wedding invitations.

You can select your favorite wedding invitations,
dress up games and begin working to give your doll a new look.
Rs2guru dresses for prom

this is definitely good for statistics. This will help you get a lot of information from it. I would love to use it.Orlando Personal Injury Lawyers

This is very useful I feel that the standard user tracking isn't sufficient and I've been seeking something better. Thanks Fake Tattoos

i think, it is very useless. no thanks webcam chat shemale

Choose, buy and shop for on sale tiffany jewelry including Tiffany & Co Silver Necklace, Pendants, Bangles, Bracelets, Earrings, Rings and Accessories.
tiffany jewelry
We will surprise to find the high quality in much.
Everyone will focus on tiffany and co
Tiffany Bracelets
Tiffany Earrings
Tiffany Necklaces
links of london

Well this is very interesting indeed. Would love to read a little more of this. Great post. Thanks for the heads-up...This blog was very informative and knowledgeable…Colon Cleanse Colon Cleanse Acai Berry

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.
Free Sports Picks | Fun Things to do in San Francisco

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.