Skip to content

Instantly share code, notes, and snippets.

@bermi
Created January 25, 2011 19:18
Show Gist options
  • Save bermi/795457 to your computer and use it in GitHub Desktop.
Save bermi/795457 to your computer and use it in GitHub Desktop.
symfony app logger for creating name-spaced logs with ease
<?php
class AppLogger
{
protected $fp = null;
public static function log($message, $priority = 'info', $namespace = 'app')
{
if(sfConfig::get('app_loggers_'.$namespace) !== false)
{
AppLogger::getInstance($namespace)->doLog($message, $priority, $namespace);
}
}
public static function &getInstance($namespace = 'app')
{
static $Loggers = array();
if(!isset($Loggers[$namespace]))
{
$Loggers[$namespace] = new AppLogger(array('file'=> sfConfig::get('sf_log_dir').'/'.$namespace.'_'.sfConfig::get('sf_environment').'.log'));
}
return $Loggers[$namespace];
}
public function __construct($options = array())
{
if (!isset($options['file']))
{
throw new sfConfigurationException('You must provide a "file" parameter for this logger.');
}
$dir = dirname($options['file']);
if (!is_dir($dir))
{
mkdir($dir, isset($options['dir_mode']) ? $options['dir_mode'] : 0777, true);
}
$fileExists = file_exists($options['file']);
if (!is_writable($dir) || ($fileExists && !is_writable($options['file'])))
{
throw new sfFileException(sprintf('Unable to open the log file "%s" for writing.', $options['file']));
}
$this->fp = fopen($options['file'], 'a');
if (!$fileExists)
{
chmod($options['file'], isset($options['file_mode']) ? $options['file_mode'] : 0666);
}
}
public function doLog($message, $priotiry = 'info', $namespace)
{
flock($this->fp, LOCK_EX);
fwrite($this->fp, strtr('%time% %type% [%priority%] %message%%EOL%', array(
'%type%' => $namespace,
'%message%' => $message,
'%priority%' => $priotiry,
'%time%' => @strftime('%b %d %H:%M:%S'),
'%EOL%' => PHP_EOL,
)));
flock($this->fp, LOCK_UN);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment