Skip to content

Instantly share code, notes, and snippets.

@lotharthesavior
Created January 15, 2020 11:34
Show Gist options
  • Save lotharthesavior/230cf493bac3bb5d33689dce17b4cf5d to your computer and use it in GitHub Desktop.
Save lotharthesavior/230cf493bac3bb5d33689dce17b4cf5d to your computer and use it in GitHub Desktop.
<?php
namespace App\Library\Services;
use Facades\Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
class CustomFileLog
{
/** @var string */
const LOG_FILE_LABEL = 'my-custom-file-';
/** @var array */
const ACCEPTED_LEVELS = [
'emergency',
'alert',
'critical',
'error',
'warning',
'notice',
'info',
'debug',
];
/** @var Logger */
protected $monolog;
/** @var \Monolog\Handler\HandlerInterface[] */
protected $originalHandlers;
private function __construct()
{
$this->monolog = Log::getMonolog();
$this->originalHandlers = $this->monolog->getHandlers();
}
/**
* @param string $data
* @param string $level
*/
public static function log(string $data, string $level = 'info'): void
{
static $instance = null;
if ($instance === null) {
$instance = new CustomFileLog();
}
if (!in_array($level, self::ACCEPTED_LEVELS)) {
Log::warning('Not valid level passed to CustomFileLog!');
return;
}
$instance->setLocalHandler();
Log::{$level}($data);
$instance->setOriginalHandler();
}
/**
* This is the reason this class is a singleton,
* if procedure set more than once it will duplicate
* logs.
*/
private function setLocalHandler(): void
{
$logDate = Carbon::now()->format('Y-m-d');
$handler = new StreamHandler(storage_path() . '/logs/' . self::LOG_FILE_LABEL . $logDate . '.log');
$this->monolog->setHandlers([$handler]);
}
private function setOriginalHandler()
{
$this->monolog->setHandlers($this->originalHandlers);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment