Rich Rich - 1 year ago 62
MySQL Question

Creating a Log system for a PHP Application

I am currently working on a PHP Application where I am trying to log user events on a specific order.

I have never created a log system, but after various researching, it seems that creating a file system for logging is the best solution.

Log information required:

1) Order Num

2) Time Stamp

2) Current User

3) Changes Made

Example: [D7293E7BB5--10/Jun/2012:10:36:19] (User_Name) Activity performed on this Order.

Main Concerns

  • Do I put all the log data of all the orders in the same file, using regex to access by Order-Num or create seperate files for seperate orders (I would think this might be too many files)?

  • Will I run into problems if more than one user performs and action on an order around the same time?

  • Is a text based file the best solution for what I am achieving?

Possible other solutions??

MongoDB, Hadoop for logs while using SQL for main DB.

Answer Source

You can store your data in a CSV file.


Order_Num, Time_Stamp, User, Changes

Then you can have a function like this which writes to this file:

function write_log($order_num,$user,$changes){
    $time_stamp = time();

    $headers = array();

    $filename = "your_filename.csv";

        $headers = array('Order_Num', 'Time_Stamp', 'User', 'Changes');

    $output = fopen($filename, 'w');

      fputcsv($output, $headers);

    fputcsv($output, array($order_num, $time_stamp, $user, $changes));


Then, to view your log, just read back from the CSV file:

function read_log(){
    $filename = "your_filename.csv";
    $file_contents = file_get_contents($filename);
    $file_content_lines = array_map("str_getcsv", preg_split('/\r*\n+|\r+/',$file_contents));

    echo "<table>";
    echo "<tr><th>Order #</th><th>Date</th><th>User</th><th>Activity</th></tr>";

    foreach($file_content_lines as $line_number => $file_content_line){
        $order_num = $file_content_line[0];
        $time_stamp = $file_content_line[1];
        $user = $file_content_line[2];
        $changes = $file_content_line[3];

        echo "<tr>$order_num<td></td><td>".date('Y-m-d H:i:s', $time_stamp)."</td><td>$user</td><td>$changes</td></tr>";

    echo "</table>";

The code is untested but it should work with minimal modifications, but the general idea is pretty clear.

I would suggest making a mechanism to save a different file for each day, i.e append a date to the filename, and implementing the feature to pass the date as a parameter to read_log() function to read only for a specific date, this way, your one csv file will not go on forever and ever.

But the possibilities are endless.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download