Skip to content

Instantly share code, notes, and snippets.

@omitobi
Created July 14, 2023 06:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omitobi/e0e9ed21ddd47fe7da4281646ccd2ff0 to your computer and use it in GitHub Desktop.
Save omitobi/e0e9ed21ddd47fe7da4281646ccd2ff0 to your computer and use it in GitHub Desktop.
Custom Laravel Logs Handler
<?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