[UPGRADE] Upgraded KLogger Library

* [REMOVED] Logfile name not possible right now
* [ADDED] All loglevels supplied by KLogger
This commit is contained in:
Sebastian Grewe 2014-02-07 13:40:50 +01:00
parent ba1dd5e8ab
commit ed0be8ec47
3 changed files with 444 additions and 167 deletions

View File

@ -5,30 +5,49 @@ class Logger {
private $logging = false; private $logging = false;
public function __construct($config) { public function __construct($config) {
if ($config['logging']['enabled'] && $config['logging']['level'] > 0) { if ($config['logging']['enabled'] && $config['logging']['level'] > 0) {
$this->KLogger = new KLogger($config['logging']['path']."/".$config['logging']['file'], $config['logging']['level']); $this->KLogger = KLogger::instance($config['logging']['path'], $config['logging']['level']);
$this->logging = true; $this->logging = true;
} }
} }
public function log($type, $message) { public function log($strType, $strMessage) {
// Logmask, we add some infos into the KLogger // Logmask, we add some infos into the KLogger
$strMask = "[ %12s ] [ %8s | %-8s ] : %s"; $strMask = "[ %12s ] [ %8s | %-8s ] : %s";
$strIPAddress = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : 'unknown'; $strIPAddress = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : 'unknown';
$strPage = isset($_REQUEST['page']) ? $_REQUEST['page'] : 'none'; $strPage = isset($_REQUEST['page']) ? $_REQUEST['page'] : 'none';
$strAction = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'none'; $strAction = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'none';
$strMessage = sprintf($strMask, $strIPAddress, $strPage, $strAction, $strMessage);
if ($this->logging) { if ($this->logging) {
switch ($type) { switch ($strType) {
case 'info': case 'emerg':
$this->KLogger->LogInfo(sprintf($strMask, $strIPAddress, $strPage, $strAction, $message)); $this->KLogger->LogEmerg($strMessage);
break; break;
case 'warn': case 'alert':
$this->KLogger->LogWarn(sprintf($strMask, $strIPAddress, $strPage, $strAction, $message)); $this->KLogger->LogAlert($strMessage);
break; break;
case 'error': case 'crit':
$this->KLogger->LogError(sprintf($strMask, $strIPAddress, $strPage, $strAction, $message)); $this->KLogger->LogCrit($strMessage);
break; break;
case 'fatal': case 'error':
$this->KLogger->LogFatal(sprintf($strMask, $strIPAddress, $strPage, $strAction, $message)); $this->KLogger->LogError($strMessage);
break; break;
case 'warn':
$this->KLogger->LogWarn($strMessage);
break;
case 'notice':
$this->KLogger->LogNotice($strMessage);
break;
case 'info':
$this->KLogger->LogInfo($strMessage);
break;
case 'fatal':
$this->KLogger->LogFatal($strMessage);
break;
case 'debug':
$this->KLogger->LogDebug($strMessage);
break;
case '':
$this->KLogger->LogFatal($strMessage);
break;
} }
return true; return true;
} else { } else {

View File

@ -12,17 +12,13 @@ $config['protect_session_state'] = false;
/** /**
* Logging * Logging
* 0 = Nothing * Emergency = 0, Alert = 1, Critical = 2
* 1 = Everything * Error = 3, Warn = 4, Notice = 5
* 2 = INFO only * Info = 6, Debug = 7, Nothing = 8
* 3 = + WARN
* 4 = + ERROR
* 5 = + FATAL
*/ */
$config['logging']['enabled'] = true; $config['logging']['enabled'] = true;
$config['logging']['level'] = 5; $config['logging']['level'] = 6;
$config['logging']['path'] = realpath(BASEPATH.'../logs'); $config['logging']['path'] = realpath(BASEPATH.'../logs');
$config['logging']['file'] = date('Y-m-d').'.security.log';
/** /**
* Memcache Rate Limiting * Memcache Rate Limiting

506
public/include/lib/KLogger.php Executable file → Normal file
View File

@ -1,148 +1,410 @@
<?php <?php
/* Finally, A light, permissions-checking logging class. /**
* * Finally, a light, permissions-checking logging class.
* Author : Kenneth Katzgrau < katzgrau@gmail.com > *
* Date : July 26, 2008 * Originally written for use with wpSearch
* Comments : Originally written for use with wpSearch *
* Website : http://codefury.net * Usage:
* Version : 1.0 * $log = new KLogger('/var/log/', KLogger::INFO);
* * $log->logInfo('Returned a million search results'); //Prints to the log file
* Usage: * $log->logFatal('Oh dear.'); //Prints to the log file
* $log = new KLogger ( "log.txt" , KLogger::INFO ); * $log->logDebug('x = 5'); //Prints nothing due to current severity threshhold
* $log->LogInfo("Returned a million search results"); //Prints to the log file *
* $log->LogFATAL("Oh dear."); //Prints to the log file * @author Kenny Katzgrau <katzgrau@gmail.com>
* $log->LogDebug("x = 5"); //Prints nothing due to priority setting * @since July 26, 2008 Last update July 1, 2012
*/ * @link http://codefury.net
* @version 0.2.0
*/
class KLogger /**
{ * Class documentation
*/
class KLogger
{
/**
* Error severity, from low to high. From BSD syslog RFC, secion 4.1.1
* @link http://www.faqs.org/rfcs/rfc3164.html
*/
const EMERG = 0; // Emergency: system is unusable
const ALERT = 1; // Alert: action must be taken immediately
const CRIT = 2; // Critical: critical conditions
const ERR = 3; // Error: error conditions
const WARN = 4; // Warning: warning conditions
const NOTICE = 5; // Notice: normal but significant condition
const INFO = 6; // Informational: informational messages
const DEBUG = 7; // Debug: debug messages
const DEBUG = 1; // Most Verbose //custom logging level
const INFO = 2; // ... /**
const WARN = 3; // ... * Log nothing at all
const ERROR = 4; // ... */
const FATAL = 5; // Least Verbose const OFF = 8;
const OFF = 6; // Nothing at all. /**
* Alias for CRIT
* @deprecated
*/
const FATAL = 2;
const LOG_OPEN = 1; /**
const OPEN_FAILED = 2; * Internal status codes
const LOG_CLOSED = 3; */
const STATUS_LOG_OPEN = 1;
const STATUS_OPEN_FAILED = 2;
const STATUS_LOG_CLOSED = 3;
/* Public members: Not so much of an example of encapsulation, but that's okay. */ /**
public $Log_Status = KLogger::LOG_CLOSED; * We need a default argument value in order to add the ability to easily
public $DateFormat = "Y-m-d G:i:s"; * print out objects etc. But we can't use NULL, 0, FALSE, etc, because those
public $MessageQueue; * are often the values the developers will test for. So we'll make one up.
*/
const NO_ARGUMENTS = 'KLogger::NO_ARGUMENTS';
private $log_file; /**
private $priority = KLogger::INFO; * Current status of the log file
* @var integer
*/
private $_logStatus = self::STATUS_LOG_CLOSED;
/**
* Holds messages generated by the class
* @var array
*/
private $_messageQueue = array();
/**
* Path to the log file
* @var string
*/
private $_logFilePath = null;
/**
* Current minimum logging threshold
* @var integer
*/
private $_severityThreshold = self::INFO;
/**
* This holds the file handle for this instance's log file
* @var resource
*/
private $_fileHandle = null;
private $file_handle; /**
* Standard messages produced by the class. Can be modified for il8n
* @var array
*/
private $_messages = array(
//'writefail' => 'The file exists, but could not be opened for writing. Check that appropriate permissions have been set.',
'writefail' => 'The file could not be written to. Check that appropriate permissions have been set.',
'opensuccess' => 'The log file was opened successfully.',
'openfail' => 'The file could not be opened. Check permissions.',
);
public function __construct( $filepath , $priority ) /**
{ * Default severity of log messages, if not specified
if ( $priority == KLogger::OFF ) return; * @var integer
*/
private static $_defaultSeverity = self::DEBUG;
/**
* Valid PHP date() format string for log timestamps
* @var string
*/
private static $_dateFormat = 'Y-m-d G:i:s';
/**
* Octal notation for default permissions of the log file
* @var integer
*/
private static $_defaultPermissions = 0777;
/**
* Array of KLogger instances, part of Singleton pattern
* @var array
*/
private static $instances = array();
$this->log_file = $filepath; /**
$this->MessageQueue = array(); * Partially implements the Singleton pattern. Each $logDirectory gets one
$this->priority = $priority; * instance.
*
* @param string $logDirectory File path to the logging directory
* @param integer $severity One of the pre-defined severity constants
* @return KLogger
*/
public static function instance($logDirectory = false, $severity = false)
{
if ($severity === false) {
$severity = self::$_defaultSeverity;
}
if ( file_exists( $this->log_file ) ) if ($logDirectory === false) {
{ if (count(self::$instances) > 0) {
if ( !is_writable($this->log_file) ) return current(self::$instances);
{ } else {
$this->Log_Status = KLogger::OPEN_FAILED; $logDirectory = dirname(__FILE__);
$this->MessageQueue[] = "The file exists, but could not be opened for writing. Check that appropriate permissions have been set."; }
return; }
}
}
if ( $this->file_handle = fopen( $this->log_file , "a" ) ) if (in_array($logDirectory, self::$instances)) {
{ return self::$instances[$logDirectory];
$this->Log_Status = KLogger::LOG_OPEN; }
$this->MessageQueue[] = "The log file was opened successfully.";
}
else
{
$this->Log_Status = KLogger::OPEN_FAILED;
$this->MessageQueue[] = "The file could not be opened. Check permissions.";
}
return; self::$instances[$logDirectory] = new self($logDirectory, $severity);
}
public function __destruct() return self::$instances[$logDirectory];
{ }
if ( $this->file_handle )
fclose( $this->file_handle );
}
public function LogInfo($line) /**
{ * Class constructor
$this->Log( $line , KLogger::INFO ); *
} * @param string $logDirectory File path to the logging directory
* @param integer $severity One of the pre-defined severity constants
* @return void
*/
public function __construct($logDirectory, $severity)
{
$logDirectory = rtrim($logDirectory, '\\/');
public function LogDebug($line) if ($severity === self::OFF) {
{ return;
$this->Log( $line , KLogger::DEBUG ); }
}
public function LogWarn($line) $this->_logFilePath = $logDirectory
{ . DIRECTORY_SEPARATOR
$this->Log( $line , KLogger::WARN ); . 'log_'
} . date('Y-m-d')
. '.txt';
public function LogError($line) $this->_severityThreshold = $severity;
{ if (!file_exists($logDirectory)) {
$this->Log( $line , KLogger::ERROR ); mkdir($logDirectory, self::$_defaultPermissions, true);
} }
public function LogFatal($line) if (file_exists($this->_logFilePath) && !is_writable($this->_logFilePath)) {
{ $this->_logStatus = self::STATUS_OPEN_FAILED;
$this->Log( $line , KLogger::FATAL ); $this->_messageQueue[] = $this->_messages['writefail'];
} return;
}
public function Log($line, $priority) if (($this->_fileHandle = fopen($this->_logFilePath, 'a'))) {
{ $this->_logStatus = self::STATUS_LOG_OPEN;
if ( $this->priority <= $priority ) $this->_messageQueue[] = $this->_messages['opensuccess'];
{ } else {
$status = $this->getTimeLine( $priority ); $this->_logStatus = self::STATUS_OPEN_FAILED;
$this->WriteFreeFormLine ( "$status $line \n" ); $this->_messageQueue[] = $this->_messages['openfail'];
} }
} }
public function WriteFreeFormLine( $line ) /**
{ * Class destructor
if ( $this->Log_Status == KLogger::LOG_OPEN && $this->priority != KLogger::OFF ) */
{ public function __destruct()
if (fwrite( $this->file_handle , $line ) === false) { {
$this->MessageQueue[] = "The file could not be written to. Check that appropriate permissions have been set."; if ($this->_fileHandle) {
} fclose($this->_fileHandle);
} }
} }
/**
* Writes a $line to the log with a severity level of DEBUG
*
* @param string $line Information to log
* @return void
*/
public function logDebug($line, $args = self::NO_ARGUMENTS)
{
$this->log($line, self::DEBUG);
}
private function getTimeLine( $level ) /**
{ * Returns (and removes) the last message from the queue.
$time = date( $this->DateFormat ); * @return string
*/
public function getMessage()
{
return array_pop($this->_messageQueue);
}
switch( $level ) /**
{ * Returns the entire message queue (leaving it intact)
case KLogger::INFO: * @return array
return "$time - INFO -->"; */
case KLogger::WARN: public function getMessages()
return "$time - WARN -->"; {
case KLogger::DEBUG: return $this->_messageQueue;
return "$time - DEBUG -->"; }
case KLogger::ERROR:
return "$time - ERROR -->";
case KLogger::FATAL:
return "$time - FATAL -->";
default:
return "$time - LOG -->";
}
}
} /**
* Empties the message queue
* @return void
*/
public function clearMessages()
{
$this->_messageQueue = array();
}
/**
* Sets the date format used by all instances of KLogger
*
* @param string $dateFormat Valid format string for date()
*/
public static function setDateFormat($dateFormat)
{
self::$_dateFormat = $dateFormat;
}
?> /**
* Writes a $line to the log with a severity level of INFO. Any information
* can be used here, or it could be used with E_STRICT errors
*
* @param string $line Information to log
* @return void
*/
public function logInfo($line, $args = self::NO_ARGUMENTS)
{
$this->log($line, self::INFO, $args);
}
/**
* Writes a $line to the log with a severity level of NOTICE. Generally
* corresponds to E_STRICT, E_NOTICE, or E_USER_NOTICE errors
*
* @param string $line Information to log
* @return void
*/
public function logNotice($line, $args = self::NO_ARGUMENTS)
{
$this->log($line, self::NOTICE, $args);
}
/**
* Writes a $line to the log with a severity level of WARN. Generally
* corresponds to E_WARNING, E_USER_WARNING, E_CORE_WARNING, or
* E_COMPILE_WARNING
*
* @param string $line Information to log
* @return void
*/
public function logWarn($line, $args = self::NO_ARGUMENTS)
{
$this->log($line, self::WARN, $args);
}
/**
* Writes a $line to the log with a severity level of ERR. Most likely used
* with E_RECOVERABLE_ERROR
*
* @param string $line Information to log
* @return void
*/
public function logError($line, $args = self::NO_ARGUMENTS)
{
$this->log($line, self::ERR, $args);
}
/**
* Writes a $line to the log with a severity level of FATAL. Generally
* corresponds to E_ERROR, E_USER_ERROR, E_CORE_ERROR, or E_COMPILE_ERROR
*
* @param string $line Information to log
* @return void
* @deprecated Use logCrit
*/
public function logFatal($line, $args = self::NO_ARGUMENTS)
{
$this->log($line, self::FATAL, $args);
}
/**
* Writes a $line to the log with a severity level of ALERT.
*
* @param string $line Information to log
* @return void
*/
public function logAlert($line, $args = self::NO_ARGUMENTS)
{
$this->log($line, self::ALERT, $args);
}
/**
* Writes a $line to the log with a severity level of CRIT.
*
* @param string $line Information to log
* @return void
*/
public function logCrit($line, $args = self::NO_ARGUMENTS)
{
$this->log($line, self::CRIT, $args);
}
/**
* Writes a $line to the log with a severity level of EMERG.
*
* @param string $line Information to log
* @return void
*/
public function logEmerg($line, $args = self::NO_ARGUMENTS)
{
$this->log($line, self::EMERG, $args);
}
/**
* Writes a $line to the log with the given severity
*
* @param string $line Text to add to the log
* @param integer $severity Severity level of log message (use constants)
*/
public function log($line, $severity, $args = self::NO_ARGUMENTS)
{
if ($this->_severityThreshold >= $severity) {
$status = $this->_getTimeLine($severity);
$line = "$status $line";
if($args !== self::NO_ARGUMENTS) {
/* Print the passed object value */
$line = $line . '; ' . var_export($args, true);
}
$this->writeFreeFormLine($line . PHP_EOL);
}
}
/**
* Writes a line to the log without prepending a status or timestamp
*
* @param string $line Line to write to the log
* @return void
*/
public function writeFreeFormLine($line)
{
if ($this->_logStatus == self::STATUS_LOG_OPEN
&& $this->_severityThreshold != self::OFF) {
if (fwrite($this->_fileHandle, $line) === false) {
$this->_messageQueue[] = $this->_messages['writefail'];
}
}
}
private function _getTimeLine($level)
{
$time = date(self::$_dateFormat);
switch ($level) {
case self::EMERG:
return "$time - EMERG -->";
case self::ALERT:
return "$time - ALERT -->";
case self::CRIT:
return "$time - CRIT -->";
case self::FATAL: # FATAL is an alias of CRIT
return "$time - FATAL -->";
case self::NOTICE:
return "$time - NOTICE -->";
case self::INFO:
return "$time - INFO -->";
case self::WARN:
return "$time - WARN -->";
case self::DEBUG:
return "$time - DEBUG -->";
case self::ERR:
return "$time - ERROR -->";
default:
return "$time - LOG -->";
}
}
}