mathewparet/laravel-global-log-context

Adds global logging context

v1.0.1 2023-08-07 09:30 UTC

This package is auto-updated.

Last update: 2024-04-07 10:52:29 UTC


README

Easily add extra logging context to all logs

Installation

Install the library

composer require mathewparet/laravel-global-log-context

Create a context definition class

// app/tools/LogContext/LogContext.php
use mathewparet\LaravelGlobalLogContext\Contracts\ContextDefinition;

namespace App\Tools\LogContext;

class LogContext implements ContextDefinition
{
    public static function context(): array
    {
        return [
            'user' => request()?->user()?->email,
            'ip' => requiest()?->ip()
        ];
    }
}

Bind this in your service provider

// app/providers/AppServiceProvider.php
namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use mathewparet\LaravelGlobalLogContext\Contracts\ContextDefinition;
use App\Tools\LogContext\LogContext;

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->bind(ContextDefinition::class, LogContext::class);
    }
}

Update logger config

// config/logging.php
// ...
use mathewparet\LaravelGlobalLogContext\ExtraLoggingContext\AddExtraContextToLogs;

return [
    // ...
    'channels' => [
        'stack' => [
            'driver' => 'stack',
            // ....
            'tap' => AddExtraContextToLogs::class
        ]
    ]
];