Search code examples
databaseandroid-activitylogging

Best practice for storing user history in DB


I need some advice... I have an application where users can do certain actions. For example, users can have friends. So... Users can see his friends activity. So how should I implement the activity log in the DB? Should I have a new table? Can I do some queries from multiple table and sort a joined result?


Solution

  • I suggest you create an activity_type table and a logs table.

    activity_type | id | name           | table
    --------------+----+----------------+-------
                     1 | added friend   | tbl_users
                     2 | added comment  | tbl_comments
                     3 | added image    | tbl_images
                     4 | Updated dp     | NULL
    

    Now you can easily maintain logs using the following table

       logs_table | id | user | activity_type  | object_id | time_stamp
    --------------+----+------+----------------+-----------+------------
                     1 | 15   | 1              | 5         | 2012-03-10 08:45:05
                     2 | 15   | 2              | 19        | 2012-03-10 08:46:05
                     3 | 15   | 3              | 84        | 2012-03-10 08:47:05
                     4 | 15   | 4              | NULL      | 2012-03-10 08:48:05
    

    User#15 added a new friend user#5 on 10th March.

    User#15 added a new comment#19 on 10th March.

    User#15 added a new image#84 on 10th March.

    User#15 changed his display picture on 10th March.

    UPDATE There may be activities where object_id doesn't make sense like- updated display image, updated profile info etc. Here you can possibly store diff of text in a separate column.

    The same approach can be used for storing audit logs.