Mainly written for fun, but this is a configurable Logger written in PHP that supports multiple handlers, including Writers (File, SQL, Apache’s Error Log, Echo), configurable Formatting. various logging levels (FATAL, ERROR, WARN, INFO, DEBUG, TRACE). Also useful functions like isDebug/TraceEnabled(), to check before building large strings to debug/trace(). *While each logger instance can have a unique name, there isn’t any parent/child hierarchy attributed to them.
update: Now on GitHub
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 | <?php /** * PHP Logger * @author Kenny Cason * @site www.ken-soft.com */ class Logger { /** * static Logger for convenient quick use of logger */ public static function getStaticLogger($resource, $config=array()) { $logger = new Logger(); $logger->resource = $resource; Logger::configure($logger, $config); return $logger; } /** * singleton instances of a Logger indexed by a unique resource */ private static $loggerInstances = array(); /* * log levels, int value */ const FATAL = 6; const ERROR = 5; const WARN = 4; const INFO = 3; const DEBUG = 2; const TRACE = 1; /* * log levels, string values */ private static $LOG_LEVELS = array( Logger::TRACE => "TRACE", Logger::DEBUG => "DEBUG", Logger::INFO => "INFO", Logger::WARN => "WARN", Logger::ERROR => "ERROR", Logger::FATAL => "FATAL"); public $handlers = array(); public $logLevel = Logger::INFO; // default logging level is info /* * formatting - move to LogFormatter Class later */ public $resource = ""; // a unique identifier for this logger (i.e. a class name, or script name) /** * using singleton pattern return a logger instance * @param string $resource * @param array configuration * @return Logger instance */ public static function getLogger($resource, $config=array()) { if (!isset(self::$loggerInstances[$resource])) { self::$loggerInstances[$resource] = new Logger(); } Logger::$loggerInstances[$resource]->resource = $resource; Logger::configure(Logger::$loggerInstances[$resource],$config); return Logger::$loggerInstances[$resource]; } private static function configure(Logger $logger, $config=array()) { if (isset($config['logLevel'])) { $logger->logLevel = $config['logLevel']; } if (isset($config['handlers']) && is_array($config['handlers'])) { $logger->clearHandlers(); $logger->handlers = $config['handlers']; } if (isset($config['handler']) && !is_array($config['handler'])) { $logger->clearHandlers(); $logger->addHandler($config['handler']); } if(empty($logger->handlers)) { $logger->addHandler(new LogFileHandler()); // create a default LogFileHandler } } public function setLevel($level=Logger::ERROR) { if($level >= Logger::TRACE && $level <= Logger::FATAL) { $this->logLevel = $level; } else { $this->logLevel = Logger::INFO; } } /** * return the current log level * @return string */ public function getLevel() { return Logger::$LOG_LEVELS[$this->logLevel]; } /** * set the log mode. (i.e.log to LOG_TYPE_FILE / LOG_TYPE_SQL / LOG_TYPE_ERROR_LOG * @param int */ public function setLogMode($logMode) { $this->logMode = $logMode; } /** * get lhe log mode * @return int */ public function getLogMode() { return $this->logMode; } /** * get all handlers */ public function getHandlers() { return $this->handlers; } /** * add a handler * @param ILogHandler $handler */ public function addHandler(ILogHandler $handler) { $this->handlers[] = $handler; } /** * clear all handlers */ public function clearHandlers() { $this->handlers = array(); } /** * determine if the logger level is at least DEBUG level * @return bool */ public function isDebugEnabled() { if($this->getLevel() <= Logger::DEBUG) { return true; } return false; } /** * determine if the logger level is at least TRACE level * @return bool */ public function isTraceEnabled() { if($this->getLevel() <= Logger::TRACE) { return true; } return false; } /** * log at trace level * @param string $msg * @param object $obj (optional) */ public function trace($msg, $obj=null) { if($this->logLevel <= Logger::TRACE) { $this->log(Logger::TRACE, $msg, $obj); } } /** * log at debug level * @param string $msg * @param object $obj (optional) */ public function debug($msg, $obj=null) { if($this->logLevel <= Logger::DEBUG) { $this->log(Logger::DEBUG, $msg, $obj); } } /** * log at info level * @param string $msg * @param object $obj (optional) */ public function info($msg, $obj=null) { if($this->logLevel <= Logger::INFO) { $this->log(Logger::INFO, $msg, $obj); } } /** * log at warn level * @param string $msg * @param object $obj (optional) */ public function warn($msg, $obj=null) { if($this->logLevel <= Logger::WARN) { $this->log(Logger::WARN, $msg, $obj); } } /** * log at error level * @param string $msg * @param object $obj (optional) */ public function error($msg, $obj=null) { if($this->logLevel <= Logger::ERROR) { $this->log(Logger::ERROR, $msg, $obj); } } /** * log at catastrophic level * @param string $msg * @param object $obj (optional) */ public function fatal($msg, $obj=null) { if($this->logLevel <= Logger::FATAL) { $this->log(Logger::FATAL, $msg, $obj); } } /** * private helper * @param int $logLevel * @param string $msg */ public function log($logLevel, $msg, $obj=null) { $record = new LogRecord(); $record->setLevel(Logger::$LOG_LEVELS[$logLevel]); $record->setMessage($msg); $record->setResource($this->resource); $record->setObject($obj); foreach($this->handlers as $handler) { $handler->publish($record); } } /** * private constructor init using getLogger() */ private function __construct() { } /** * Prevent users to clone the instance */ public function __clone() { $this->log('Clone is not allowed.'); } } /** * This class encapsulates the Record to be logged */ class LogRecord { private $resource; private $level; private $msg; private $obj; // optional object to log along with $msg private $time; public function __construct() { $this->time = time(); } public function setResource($resource) { $this->resource = $resource; } public function setLevel($level) { $this->level = $level; } public function setMessage($msg) { $this->msg = $msg; } public function setObject($obj) { $this->obj = $obj; } public function setTime($time) { $this->time = $time; } public function getResource() { return $this->resource; } public function getLevel() { return $this->level; } public function getMessage() { return $this->msg; } public function getObject() { return $this->obj; } public function getTime($format=null) { if($format == null) { return $this->time; } return date($format, $this->time); } } /** * LogHandler interface */ interface ILogHandler { public function publish(LogRecord $record); public function setFormatter(ILogFormatter $formatter); public function getFormatter(); } /** * contains common functionality between log handlers */ abstract class AbstractLogHandler implements ILogHandler { protected $formatter; public function __construct() { $this->formatter = new LogDefaultFormatter(); } public function setFormatter(ILogFormatter $formatter) { $this->formatter = $formatter; } public function getFormatter() { return $this->formatter; } } /** * Outputs to a LogFile */ class LogFileHandler extends AbstractLogHandler { private $logFileName = "/tmp/output.log"; public function __construct($logFileName="") { parent::__construct(); if($logFileName != "") { $this->logFileName = $logFileName; } } public function publish(LogRecord $record) { $log_msg = $this->formatter->format($record); $logFile = fopen($this->logFileName, 'a'); if (!$logFile) { return array('status' => 'failure', 'msg' => 'Error Opening Log File'); } fwrite($logFile, $log_msg); fclose($logFile); } /** * set the log file name to append to * @param string */ public function setLogFileName($logFileName) { $this->logFileName = $logFileName; } public function getLogFileName() { return $this->logFileName; } } /** * Echo out the Log */ class LogConsoleHandler extends AbstractLogHandler { public function __construct() { parent::__construct(); } public function publish(LogRecord $record) { echo $this->formatter->format($record); } } /** * Log via error_log() */ class LogApacheErrorLogHandler extends AbstractLogHandler { public function __construct() { parent::__construct(); } public function publish(LogRecord $record) { error_log($this->formatter->format($record)); } } /** * Logs to SQL DataBase */ class LogSQLHandler extends AbstractLogHandler { private $db = null; // mysqli instance public function __construct($db) { $this->db = $db; } public function publish(LogRecord $record) { $sql = "INSERT INTO `log` (log_level, date, resource, msg) VALUES ('{$record->getLevel()}','{$record->getTime()}', ?, ?);"; $statement = $this->db->prepare($sql); $statement->bind_param("ss", $record->getResource(), $record->getMessage()); if (!$statement->execute()) { return array('status' => 'failure', 'msg' => 'SQL Error'); } $statement->close(); } public function setDB(mysqli $db) { $this->db = $mysqli; } public function getDB() { return $this->db; } public static function init() { $sql = "CREATE TABLE `log` ( `id` BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, `log_level` VARCHAR( 16 ) NOT NULL, `date` DATETIME NOT NULL, `resource` VARCHAR( 128 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, `msg` VARCHAR( 1024 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL ) ENGINE = MYISAM;"; $this->db->query($sql); } } /** * Interface for formatting log messages */ interface ILogFormatter { public function format(LogRecord $record); } /** * concrete implementation of a Log Formatter that is formattable * %L - Log Level * %T - Time of logging * %R - Resource of the logger * %M - The Message * %O - The Object */ class LogFormatter implements ILogFormatter { private $format = null; private $dateFormat = "Y-m-d H:i:s"; public function __construct($format="%L [%T] %R %M %O") { $this->format = $format; } /** * return a formatted string * @param LogRecord $record */ public function format(LogRecord $record) { $formatted_record = $this->format; $formatted_record = str_replace("%L",$record->getLevel(),$formatted_record); $formatted_record = str_replace("%T",$record->getTime($this->dateFormat),$formatted_record); $formatted_record = str_replace("%R",$record->getResource(),$formatted_record); $formatted_record = str_replace("%M",$record->getMessage(),$formatted_record); $formatted_record = str_replace("%O",$record->getObject(),$formatted_record); return $formatted_record; } public function setDateFormat($dateFormat) { $this->dateFormat = $dateFormat; } } /** * Default log formatter, format is immutable, but should suffice for most cases */ class LogDefaultFormatter implements ILogFormatter { private $dateFormat = "Y-m-d H:i:s"; public function __construct() { } public function format(LogRecord $record) { return "{$record->getLevel()}\t[{$record->getTime($this->dateFormat)}]\t{$record->getResource()}\t{$record->getMessage()}\t".print_r($record->getObject(),1)."\n"; } } ?> |
A simple Demo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 | <?php require_once("DBConfig.php"); // <-- DB stuff only really needed if you want to use the SQL writer. require_once("Logger.php"); $db = new mysqli($DB_HOST, $DB_USER, $DB_PASSWORD, $DB_DATABASE,$DB_PORT); $db->set_charset("utf8"); // check connection if (mysqli_connect_errno()) { printf("DB Connection failed: %s\n", mysqli_connect_error()); exit(); } /* * out of class example */ //$logger = Logger::getLogger(__FILE__); //$logger->addHandler(new LogConsoleHandler()); //$logger->addHandler(new LogFileHandler("/tmp/output.log")); //$logger->addHandler(new LogSQLHandler($db)); /* * in class example */ $foo = new Foo($db); $foo->bar(); class Foo { private $logger; public function __construct($db) { /* * A simple Logger with default Formatter and a Default LogFileHandler (prints out to /tmp/output.log */ $this->logger = Logger::getLogger(__CLASS__, array("logLevel" => Logger::TRACE)); /** * add a custom Formatter */ $this->logger->clearHandlers(); // this clears the default handler (i may make this happen invisibly later) $fh = new LogFileHandler("/tmp/output.log"); $fh->setFormatter(new LogFormatter("%L --- %R --- (%T) --- %M %O\n")); $this->logger->addHandler($fh); // $this->logger = Logger::getLogger(__CLASS__, array("logLevel" => Logger::TRACE, // "handlers" => array(new LogFileHandler("/tmp/output3.log"), new LogSQLHandler($db), new LogConsoleHandler(), new LogErrorLogHandler()) // )); print_r($this->logger); } public function bar() { $this->logger->trace("A Trace Statement (Level INFO)"); $this->logger->debug("A Debug Statement (Level INFO)"); $this->logger->info("An Info level msg (Level INFO)"); $this->logger->warn("A Warning Occured (Level INFO)"); $this->logger->error("An Error Occured (Level INFO)"); $this->logger->fatal("A Fatal Error occured (Level INFO)"); $this->logger->setLevel(Logger::TRACE); $this->logger->trace("A Trace Statement (Level TRACE)"); $this->logger->debug("A Debug Statement (Level TRACE)"); $this->logger->info("An Info level msg (Level TRACE)", $this); $this->logger->warn("A Warning Occured (Level TRACE)"); $this->logger->error("An Error Occured (Level TRACE)"); $this->logger->fatal("A Fatal Error occured (Level TRACE)"); $this->logger->setLevel(Logger::FATAL); $this->logger->trace("A Trace Statement (Level FATAL)"); $this->logger->debug("A Debug Statement (Level FATAL)"); $this->logger->info("An Info level msg (Level FATAL)"); $this->logger->warn("A Warning Occured (Level FATAL)", $this); $this->logger->error("An Error Occured (Level FATAL)"); $this->logger->fatal("A Fatal Error occured (Level FATAL)"); if($this->logger->isDebugEnabled()) { $this->logger->debug("First Debug Statement (shouldn't be printed)"); } $this->logger->setLevel(Logger::DEBUG); if($this->logger->isDebugEnabled()) { $this->logger->debug("Second Debug Statement (should be printed)"); } if($this->logger->isTraceEnabled()) { $this->logger->trace("First Trace Statement (shouldn't be printed)"); } $this->logger->setLevel(Logger::TRACE); if($this->logger->isTraceEnabled()) { $this->logger->trace("Second Trace Statement (should be printed)"); } } public function __toString() { return "ASFASDFASDF"; } } echo "<br/>Test Complete<br/>"; ?> |


Posted in
Tags: 
