Why this site looks better in Firefox
Thumbnail
Borrow my code

Feel free to borrow any code you like on this site for modification and use on your site. For support implementing just leave a comment for Cd&. You will also find Cd& providing answers and solutions on codingforums, Experts-Exchange, and other help sites where support is available. If there is a snippet you need for your web site, send a request to Cd&, and it might end up being made available on the site.

If you use code from coboldinosaur.com a link would be appreciated.

If you have code on your site that might help other developers, you could add a Borrow button and join the movement to make good open source code easily accessible to all developers.

Dzone icon Reddit icon Facebook icon RSS Icon

COBOLdinosaur


Custom Logging Site Events


Submitted by: COBOLdinosaur on 2012-07-19 13:39:10

Member Site: http://COBOLdinosaur.com

So you are tired of digging through the system logs and error logs; or you have jobs running where you want to do custom logging. Okay here is the solution. Set up your own logging system and only log the events that you need to know about or want to analyze. Of course there is already a logging capbility in php, but it requires setup for custom logging, and on some hosts you may not have the access you need to do a simple thing like:

if ($msgCode>2)
{
    logAction($jobName,$msgCode,'text message');
    // do some other stuff
}

Ah yes! If it was just that easy. Just call a function... but where do you get the function? Right here! Just read on.

Any job or script that needs the function, gets enabled by putting this in the page:
require_once(yoursite/path/actionLog.inc');. The actionLog.inc will contain your custome code.

The Action Log Code

<?php
// first we declare a class to handle the file operations.
class logfile{
function write($logString )
{
    if( $handle = @fopen( '../logs/actionLog.txt', 'a+' ) ) 
    // this can be parameratized
    {
        $logString .="\n"; // insures each entry is on a new line
        fputs( $handle, $logString, strlen($logString) );
        fclose( $handle );
        return( true );
    }
    else
    {
        return( false );
    }
}
} // end logfile class

function logAction($job,$cd,$msg)
{
    // now we can create the custom code using the class
    $msgTypes=explode(',',"INFO,PROGRESS,WARN,ERROR,SECURITY,INVALID"); 
    //invalid must always be the last entry ... add more if needed
    $cod = ($cd>=count($msgTypes)) ? (count($msgTypes) - 1) : $cd;
    // If the code is invalid return INVALID as the message type
    $dt=date("Y-m-d H:i:s"); 
    // customize the date format to fit your requiremments
    $theLog = new logfile();
    // an instance of the logfile class
    $msgStr=$msgTypes[$cod].'{'.$cd.'}: '.$job.': '.$dt.'>>> '.$msg; 
    // create the log message
    $theLog->write($msgStr); // this fires the file handling in the class
}
?>

So we have the function all hooked up but where are we getting the values for the three parameter? Back to the calling script.

The three passed parameters could be literals if we are only going to log in one script, but you probably want it more flexible than that so back in the calling script; which could be in a CRON job, a form handler, or a page generator. We do a little preparation by declaring the variables.

It will look something like this:

    require_once(yoursite/path/actionLog.inc');
    // that includes the class in your script
    $theJob ='yourScript.php';
    // there is the job name we want to show in the log
    $startCode=0;
    $endCode=0;
    $processingCode=1;
    $errorCode=2;
    // here we have set the message codes we might use in the script
    $startMsg='Job started';
    $endMsg='Job completed';
    $procMsg='Created outputFiles/myData.txt:';
    $openFailMsg='Failed on file open for output';
    // And the text of the messages so we don't have to guess the cause
    logAction ($theJob, $startCode, $startMsg);
    // Might as well send a message that the job has started
    // how do we log an error?
    // LIKE THIS:
    
    if ($weGotAnErrorOnOpen}
    {
        logAction($jobName,$errorCode,$openFailMsg);
    }
    
    // By pre-defining all the values for the logging we reduce the code 
    // to a simple if instruction
    

Now the job is set up to log messages anywhere you need them with:
logAction($jobName,$msgCode,$msg);
The resulting log entries might look like:

PROGRESS{1}: yourScript.php: 2012-02-02 21:12:49>>> Created outputFiles/myData.txt
ERROR{1}: yourScript.php: 2012-02-02 21:12:50>>> Failed on file open for output
INFO{0}: yourScript.php: 2012-02-02 21:12:50>>> Job completed

In your log messages you can include any variable, including the $_SESSION, $_POST or anything else you need to track. Everything is contained on the server, so you do not have security issues, as long as you restrict access to the log files.The class is looking for a variable length string, so you can send it whatever you need.

Because the log is a text file it can be opened in any text editor. You can format it anyway you want, and add any additional parameters you need. You can also output the log as comma separated variables ready to be imported to a database table. When you get real ambitious you could even output in a script format so you can go straight into your database. An XML file; JSON formatted dataset; even tagged with HTML and CSS if you want. You can also combine different logs into a master log if you want to run separate logs for each job you run. You could also write a parser to create custom reports from the logs.

Got a special script or snippet? Author Guidelines

To comment on this snippet LOGIN or REGISTER FOR FREE
Want to talk about this page? Send a comment to Cd&
Not a member of COBOLdinosaur yet? FREE REGISTRATION HERE