Thursday, December 10, 2009

Write messages in a log file


In this example, we implement a log file.

Components used in this example
Implementation of the log process
  • We define the set of the available priorities.

class MyLog
{
    const 
FORMAT '%timestamp% %priorityName% (%priority%): %message%';

    
// We define the set of the available priorities.
    
private $_priorities = array(
        
'EMERG' => Zend_Log::EMERG,
        
'ALERT' => Zend_Log::ALERT,
        
'CRIT' => Zend_Log::CRIT,
        
'ERR' => Zend_Log::ERR,
        
'WARN' => Zend_Log::WARN,
        
'NOTICE' => Zend_Log::NOTICE,
        
'INFO' => Zend_Log::INFO,
        
'DEBUG' => Zend_Log::DEBUG,
    );
Logging the message
  • We get the message, the priority, the formatter, the custom format, the filter, or the log removal request, from the GET request.
  • We get the file name.
  • If the user requested to remove the logs, we delete the file.
  • Otherwise, we instantiate the log object.
  • We add the writing adapter.
  • If the user requested a filter, we add the filter.
  • We write the message into the log file.
  • If we catch an exception, we return the error message.

    public function process()
    {
        
// We get the message, the priority, the formatter, the custom format, the filter,
        // or the log removal request, from the GET request.
        
list($message$priority$formatter$format$filter$remove) =
            
$this->_getParameters();

        try {
            
// We get the file name.
            
$file $this->_getFile();

            if (
$remove) {
                
// If the user requested to remove the logs, we delete the file.
                
@unlink($file);
                
setcookie('log'''1'/');
                
$result 'The messages have been removed!';
            } else {
                
// Otherwise, we instantiate the log  object.
                
$logger = new Zend_Log;

                
// We add the writing adapter.
                
$writer $this->_setWriter($file$formatter$format);
                
$logger->addWriter($writer);

                if (isset(
$this->_priorities[$filter])) {
                    
// If the user requested a filter, we add the filter.
                    
$logFilter = new Zend_Log_Filter_Priority($this->_priorities[$filter]);
                    
$logger->addFilter($logFilter);
                }

                if (
$message) {
                    
// We write the message into the log file.
                    
$logger->log($message$this->_priorities[$priority]);
                    
$result 'The message is logged if not filtered!';
                } else {
                    
$result 'Please enter a message!';
                }
            }


        } catch (
Exception $e) {
            
// If we catch an exception, we return the error message.
            
$result $e->getMessage();
        }

        
$logs = @file_get_contents($file) or $logs 'There are no messages';

        return array(
$message$priority$formatter$format$filter$remove,
            
$result$logs);
    }
Extraction of the parameters from the GET request
  • We set the priority to the emergency level by default.
  • We ignore the filter if the filter is invalid.

    private function _getParameters()
    {
        
$message = isset($_GET['message'])? trim($_GET['message']) : null;
        
$formatter = isset($_GET['formatter'])? $_GET['formatter'] : null;
        
$format = empty($_GET['format'])? self::FORMAT $_GET['format'];

        
// We set the priority to the emergency level by default.
        
$priority = (isset($_GET['priority']) and isset($this->_priorities[$_GET['priority']]))?
            
$_GET['priority'] : 'EMERG';
        
// We ignore the filter if the filter is invalid.
        
$filter = (isset($_GET['filter']) and isset($this->_priorities[$_GET['filter']]))?
            
$_GET['filter'] : null;

        
$remove = !empty($_GET['remove']);

        return array(
$message$priority$formatter$format$filter$remove);
    }
Getting a log file name
  • If the cookie does not exist, we create the name of the file randomly. And we store the name in the cookie.
  • If the cookie exists, we get the name of the file from the cookie.

    private function _getFile()
    {
        if (empty(
$_COOKIE['log'])) {
            
// If the cookie does not exist, we create the name of the file randomly.
            // And we store the name in the cookie.
            
$file dirname(__FILE__) . '/data/log/file-' rand() . '.txt';
            
setcookie('log'$filetime() + 3600'/');
        } else {
           
// If the cookie exists, we get the name of the file from the cookie.
           
$file $_COOKIE['log'];
        }

        return 
$file;
    }
Creation of the writing adapter
  • We create an XML adapter or a simple adapter. The simple adapter will use the custom format.

    private function _setWriter($file$formatter$format)
    {
        
$writer = new Zend_Log_Writer_Stream($file);

        
// We create an XML adapter or a simple adapter.
        // The simple adapter will use the custom format.
        
$logFormatter $formatter == 'XML'? new Zend_Log_Formatter_Xml():
            new 
Zend_Log_Formatter_Simple($format PHP_EOL);

        
$writer->setFormatter($logFormatter);

        return 
$writer;
    }

}

No comments:

Post a Comment