Created
January 25, 2011 19:18
-
-
Save bermi/795457 to your computer and use it in GitHub Desktop.
symfony app logger for creating name-spaced logs with ease
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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