Created
July 14, 2023 06:49
-
-
Save omitobi/e0e9ed21ddd47fe7da4281646ccd2ff0 to your computer and use it in GitHub Desktop.
Custom Laravel Logs Handler
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 | |
declare(strict_types=1); | |
namespace App\ExampleDirectory\Loggers; | |
use Monolog\Handler\HandlerInterface; | |
use Monolog\Logger as MonologLogger; | |
use Illuminate\Log\Logger; | |
use Psr\Log\LoggerInterface; | |
class CustomContext | |
{ | |
public function __invoke(array $config): LoggerInterface | |
{ | |
// The config must at least contain a path and a level key. | |
$logger = new MonologLogger('example'); | |
$logger->pushHandler($this->getMonologHandler($config)); | |
return new Logger($logger); | |
} | |
protected function getMonologHandler(array $config): HandlerInterface | |
{ | |
$handler = new \Monolog\Handler\StreamHandler( | |
$config['path'], | |
$config['level'] | |
); | |
$handler->pushProcessor(function ($record) { | |
// Add your custom logic here to modify the log context. | |
$record['context']['user_info'] = [ | |
'ip' => request()->ip(), | |
'uid' => auth()->id() ?? 'anon', | |
'path' => request()->path(), | |
'method' => request()->getMethod(), | |
'device' => request()->header('User-Agent'), | |
]; | |
return $record; | |
}); | |
return $handler; | |
} | |
} | |
--- | |
// In config/logging.php | |
'super_log' => [ | |
'driver' => 'custom', | |
'path' => storage_path('logs/laravel.log'), | |
'via' => \App\ExampleDirectory\Loggers\CustomContext::class, | |
'level' => 'debug', | |
'days' => 90, | |
], | |
// Set this super_log as the LOG_CHANNEL |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment