codeinternetapplications / monolog-stackdriver

Stackdriver handler for Monolog.
MIT License
15 stars 15 forks source link

Allow one to adjust the "global" logger options at runtime #3

Closed bramus closed 5 years ago

bramus commented 5 years ago

This PR will allow one to adjust the $loggerOptions at runtime. One can set (override) options, or append options.

This can be handy for setting extra labels to use with all future log events, after a logger/StackdriverHandler has already been instantiated.

Usage:

use Monolog\Logger;
use CodeInternetApplications\MonologStackdriver\StackdriverHandler;

// ( ... )

// init handler
$stackdriverHandler = new StackdriverHandler(
    $projectId,
    $loggingClientOptions
);

// init logger with StackdriverHandler
$logger = new Logger('stackdriver', [$stackdriverHandler]);

// basic info log with contextual data
$logger->info('New order', ['orderId' => 1001]);

// ( ... )

// Set labels, for all future log events
$stackdriverHandler->appendLoggerOptions('labels', [
    'order' => 'paid',
]);

$logger->info('Order updated'); // Will include the order:paid label

// ( ... )
martinatcode commented 5 years ago

Hello Bramus,

Thank you for the pull request. Unfortunately, I don't feel much for such an option because this way your log is influenced by this 'hidden' options being set. If you reuse the same logger instance at different locations/contexts, you need to unset/set/unset/set those options fitting it's context. I find these options log entry specific.

As an alternative you can maintain the second log argument to reuse options you like. Example:

( ... )
// init logger with StackdriverHandler
$logger = new Logger('stackdriver', []);

// init log default context that will be reused
$logDefaultContext = [
    'stackdriver' => [
        'labels' => [
            'order' => 'paid'
        ]
    ]
];

// log specific context
$logSpecificContext = ['orderId' => 1001];

// merge log specific contextual data in your defaults
$logContext = array_merge($logDefaultContext, $logSpecificContext);

// basic info log with contextual data
$logger->info('New order', $logContext);

This sample just uses a basic array but you can wrap this array within a class where you're able to use methods like appendLoggerOptions().

I therefor will close this pull request without merging.

With kind regards Martin