Code snippets for symfony 1.x

Navigation

Refine Tags

Snippets tagged "syslog"

SysLogger

This snippet shows an implementation of a logger that logs to the syslog

<?php
class SysLogger extends sfLogger
{
  const LOG_NAME = 'SymfonySysLogger';
 
  protected
    $timeFormat = '%b %d %H:%M:%S', 
    $format     = '[%priority%] %message%';
 
 
  /**
   * Initializes this logger.
   *
   *
   * @param  sfEventDispatcher $dispatcher  A sfEventDispatcher instance
   * @param  array             $options     An array of options.
   *
   * @return Boolean      true, if initialization completes successfully, otherwise false.
   */
  public function initialize(sfEventDispatcher $dispatcher, $options = array())
  {
    $appName = $this->getApplicationName();
 
    openlog($appName, LOG_PID, LOG_USER);
 
    return parent::initialize($dispatcher, $options);
  }
 
  /**
   * this method tries to resolve the request url of a web app, or
   * the terminal arguments of a console app
   * else a default app-name is returned 
   * 
   * @return string the applicationName
   */
  protected function getApplicationName()
  {
    $appName = 'unknown-app';
    // request url or 
    if (isset($_SERVER['REQUEST_URI']))
    {
      $appName = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; 
    }
    // else console arguments
    elseif (implode($_SERVER['argv'], ' '))
    {
      $appName = implode($_SERVER['argv'], ' ');
    }    
 
    $appName = self::LOG_NAME.'(' // the default name, so infra can filter +
      .$appName.')';
 
    return $appName; 
  }
 
  /**
   * Logs a message.
   *
   * @param string $message   Message
   * @param string $priority  Message priority
   */
  protected function doLog($message, $priority)
  {
    $logMessage = strtr($this->format, array(
      '%message%'  => $message,
      '%time%'     => strftime($this->timeFormat),
      '%priority%' => $this->getPriority($priority),
    ));
 
    syslog($priority, $logMessage);
  }
 
  /**
   * Returns the priority string to use in log messages.
   *
   * @param  string $priority The priority constant
   *
   * @return string The priority to use in log messages
   */
  protected function getPriority($priority)
  {
    return sfLogger::getPriorityName($priority);
  }  
 
 
  /**
   * Executes the shutdown method.
   */
  public function shutdown()
  {
    closelog();
  }  
}
 
by Leon van der Ree on 2011-02-10, tagged log  syslog