Skip to content

Instantly share code, notes, and snippets.

@omitobi
Created July 14, 2023 06:49
Show Gist options
  • Select an option

  • Save omitobi/e0e9ed21ddd47fe7da4281646ccd2ff0 to your computer and use it in GitHub Desktop.

Select an option

Save omitobi/e0e9ed21ddd47fe7da4281646ccd2ff0 to your computer and use it in GitHub Desktop.

Revisions

  1. omitobi created this gist Jul 14, 2023.
    60 changes: 60 additions & 0 deletions custom_logs_handler.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,60 @@
    <?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