Created
August 5, 2023 14:41
-
-
Save finagin/168c9e5072560097b798a596362237ef to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
namespace Finagin\Support\Logging\Handlers; | |
use Monolog\Handler\StreamHandler; | |
use Monolog\Logger; | |
use Monolog\Processor\IntrospectionProcessor; | |
use Monolog\Utils; | |
class ClassFile extends StreamHandler | |
{ | |
/** | |
* @var string | |
*/ | |
private $basePath; | |
private $streams = []; | |
/** | |
* @param string $path | |
* @param string|int $level | |
* @param bool $bubble | |
* | |
* @throws \Exception | |
*/ | |
public function __construct(string $path, $level = Logger::DEBUG, bool $bubble = false) | |
{ | |
parent::__construct($path, $level, $bubble); | |
$this->pushProcessor( | |
new IntrospectionProcessor($level, [ | |
'Illuminate\\', | |
]) | |
); | |
$this->basePath = $path; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
protected function write(array $record) | |
{ | |
$this->url = $this->getFilename($record); | |
$this->stream = $this->streams[$this->url] ?? null; | |
parent::write($record); | |
if (! in_array($this->stream, $this->streams)) { | |
$this->streams[$this->url] = $this->stream; | |
} | |
$this->url = null; | |
parent::close(); | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function close() | |
{ | |
collect($this->streams) | |
->filter(function ($stream) { | |
return is_resource($stream); | |
}) | |
->each(function ($stream) { | |
fclose($stream); | |
}); | |
parent::close(); | |
} | |
protected function getFilename(array $record): string | |
{ | |
$file = pathinfo(str_replace(base_path(), '', | |
$record['extra']['file'] ?? null | |
)); | |
$dirname = $file['dirname'] ?? ''; | |
$filename = ($file['filename'] ?: 'unrecognized-class-file').'.log'; | |
return Utils::canonicalizePath( | |
$this->basePath.$dirname.DIRECTORY_SEPARATOR.$filename | |
); | |
} | |
} |
This file contains hidden or 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 | |
return [ | |
// ... | |
'channels' => [ | |
// ... | |
'class' => [ | |
'driver' => 'monolog', | |
'handler' => env('APP_DEBUG', false) && class_exists(\Finagin\Support\Logging\Handlers\ClassFile::class) | |
? \Finagin\Support\Logging\Handlers\ClassFile::class | |
: \Monolog\Handler\NullHandler::class, | |
'with' => [ | |
'path' => base_path(env('LOG_CLASS_PATH','storage/logs')), | |
], | |
], | |
], | |
]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment