Skip to content

Instantly share code, notes, and snippets.

@laverboy
Last active May 16, 2023 10:34
  • Star 21 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save laverboy/fd0a32e9e4e9fbbf9584 to your computer and use it in GitHub Desktop.
A simple, static, logging singleton class
<?php
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;
class Log {
protected static $instance;
/**
* Method to return the Monolog instance
*
* @return \Monolog\Logger
*/
static public function getLogger()
{
if (! self::$instance) {
self::configureInstance();
}
return self::$instance;
}
/**
* Configure Monolog to use a rotating files system.
*
* @return Logger
*/
protected static function configureInstance()
{
$dir = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'log';
if (!file_exists($dir)){
mkdir($dir, 0777, true);
}
$logger = new Logger('RdLotteryManager');
$logger->pushHandler(new RotatingFileHandler($dir . DIRECTORY_SEPARATOR . 'main.log', 5));
//$logger->pushHandler(new LogglyHandler('eeb5ba83-f0d6-4273-bb1d-523231583855/tag/monolog'));
self::$instance = $logger;
}
public static function debug($message, array $context = []){
self::getLogger()->addDebug($message, $context);
}
public static function info($message, array $context = []){
self::getLogger()->addInfo($message, $context);
}
public static function notice($message, array $context = []){
self::getLogger()->addNotice($message, $context);
}
public static function warning($message, array $context = []){
self::getLogger()->addWarning($message, $context);
}
public static function error($message, array $context = []){
self::getLogger()->addError($message, $context);
}
public static function critical($message, array $context = []){
self::getLogger()->addCritical($message, $context);
}
public static function alert($message, array $context = []){
self::getLogger()->addAlert($message, $context);
}
public static function emergency($message, array $context = []){
self::getLogger()->addEmergency($message, $context);
}
}
<?php
Log::info("something really interesting happened", ['extra' => 'information', 'about' => 'anything' ]);
@usefksa
Copy link

usefksa commented Feb 9, 2018

Thanks

@kachraf
Copy link

kachraf commented Feb 28, 2018

hello, you must make private __construct(){}, otherwise we can create an instance by new Log() and without using get->getLogger()

@slawkens
Copy link

Your protected static function configureInstance() doesn't return anything, so this is wrong:

* @return Logger

Except this, thank you very much!

@simmbiote
Copy link

Useful, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment