Sunday, March 15, 2015

Logging To File Or Email In PHP

Logging is one of the most important things in software engineering to record important code execution, as well as for debugging.

This is a simple PHP function for logging error and info, by sending email notification or logging to file, with the option to record a different timezone:

<?php

/**
* Logs an error.
*/
function logError($logMessage, $sourceFile)
{
    logInfo($logMessage, $sourceFile, "", true);
}

/**
* Logs an information.
*/
function logInfo($logMessage, $sourceFile, $logTtle = "", $isError = false)
{
    $logEmail       = "admin@example.com";      // Email address to send the logging message. Set to empty to disable it.
    $logFile        = "";                       // File name to store the logging message. Set to empty to disable it.
    $logTimezone    = "Europe/London";          // Set the additional datetime timezone shown in the logging message. Put empty to only show the default.
    
    $now            = new DateTime();           // Get current datetime in the default timezone.
    
    $logMsg = '[' . $now->format("Y-m-d H:i:s e") . ']' . "\r\n" . '[' . $sourceFile . ']' . "\r\n" . $logMessage . "\r\n\r\n";
    
    if ($logTimezone != "")
    {
        // Convert $now to the provided timezone and append at front as additional datetime.
        $now->setTimezone(new DateTimeZone($logTimezone));
        $logMsg = '[' . $now->format("Y-m-d H:i:s e") . '] ' . $logMsg;
        // ==
    }
    
    if ($logFile != "") {
        if ($isError)
            error_log($logMsg, 3, $logFile);
        else
            file_put_contents($logFile, $logMsg, FILE_APPEND | LOCK_EX);
    }
    
    if ($logEmail != "") {
        if ($isError)
            error_log($logMsg, 1, $logEmail);
        else
            mail($logEmail, $logTtle, $logMsg, "From: Notification Admin <noti@example.com>");
    }
}

Usage example:

<?php

try
{
    ...
    ...
    logInfo("Process completed successfully.", __FILE__, "Process Completed");
}
catch(Exception $e)
{
    logError("Process Exception: " . $e->getMessage() . ". Exception on line: " . $e->getLine(), __FILE__);
    exit;
}
?>


If you find this post helpful, would you buy me a coffee?


No comments:

Post a Comment