PHP code example of decahedron / monolog-sticky-context

1. Go to this page and download the library: Download decahedron/monolog-sticky-context library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

decahedron / monolog-sticky-context example snippets




$logger = new Monolog\Logger('sticky');
$logger->pushProcessor(function ($record) {
    $record['extra']['user'] = user()->id ?? null;
});


// ...

$logger = new Monolog\Logger('sticky');
$logger->pushProcessor(new StickyContextProcessor);

StickyContext::add('user', user()->id ?? null);


use Decahedron\StickyLogging\StickyContextProcessor;

$logger = new Monolog\Logger('sticky');
$logger->pushProcessor(new StickyContextProcessor);

use Decahedron\StickyLogging\Laravel\UseStickyLogging;

return [
    ...
    
    'channels' => [
        'single' => [
            'driver' => 'single'
            'path'   => storage_path('logs/laravel.log'),
            'level'  => 'debug',
            'tap'    => [UseStickyLogging::class]
        ],
        
        ...
    ]
]

if (auth()->check()) {
    StickyContext::add('user', user()->id)
}

// $logger->level(...) will now attach the sticky context data in `extra`

StickyContext::disable();
$logger->debug(...);
StickyContext::enable();

StickyContext::add('user', 1);
$logger->info('Something happened');        // This will ext is now empty and not 

StickyContext::add('user', function () {
    return user()->id;
});

// Somewhere in the package
StickyContext::stack('my_package')->add('request_id', Uuid::uuid4()->toString());

// In the application
StickyContext::add('user', user()->id);

[
    'sticky' => [
        'user' => 1,
    ],
 
    'my_package' => [
        'request_id' => '91c9dc1e-11ed-46ff-8598-701a9f93eb2b',
    ],
]

StickyContext::defaultStack('application');