Logging user activity

Cameron Simpson cs at cskk.id.au
Mon Feb 7 17:40:40 EST 2022


On 06Feb2022 23:30, blessy carol <carolblessy15 at gmail.com> wrote:
>I have this task where I have to create log files to record user 
>activity whenever they make an entry or view something. Also, I have to 
>create Database log file whenever someone accessed or manipulated the 
>data in the database. The code is written python and used django 
>framework. I've connected django with oracle cloud database. So now I 
>want to if the basic logging details can be used to store the record of 
>these activities in the log file in the server. It  would be of great 
>help.

For the file, you can do that directly in the logging configuration - 
there's a FileHandler with a bunch of configuration options (like 
rolling over to a new file etc). Hook that to your logging setup.

For the db side, make a Djanog Model for your log table and write your 
own logging handler which makes new instance of the model containing log 
information. There might even by a prebuilt Django logging thing 
available for that - I haven't looked.

We had a "log everything!" requests for a project here.

I made a generic AuditLog Django model for this. It has a timestamp, a 
description, a log_type PositiveIntegerField, a user field (because we 
were tracking things by User, can be NULL for things not driven by a 
User eg app internals), a parent (ForeignKey to the AuditLog model so 
you can make hierarchical related log entries), and an:

    entity = GenericForeignKey("entity_type", "entity_uuid")

which was a reference to some "primary" entity (Model instance) 
elsewhere where that was relevant, and a couple of JSON fields for state 
information.

This is massive overkill for your needs, but we only wanted to do this 
once, so needs like yours also use this model here.

Then you can write simple log calls which make model instances with what 
you need to log in them.

The only only real catch for us was transactions - if something fails 
and rolls back the transaction it also throws away the log entries 
because they're in the transaction. For your needs that is probably 
fine.

For us, we want to use it for error tracking/diagnosis too, so I've got 
a ticket to hand the logging to a distinct Thread (which magicly makes a 
distinct db connection, outside the transaction). That way the logging 
can survive a transaction rollback.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Python-list mailing list