laravel / ideas

Issues board used for Laravel internals discussions.
938 stars 31 forks source link

"Lifecycle" Events for logging #2639

Open Kazuto opened 3 years ago

Kazuto commented 3 years ago

Hey guys,

I think having two events (before and after) for writeLog() would be beneficial for many projects.

E.g. I'm currently stuck trying to add a globally consistent "default" context to log messages so that I and other devs won't have differences while logging information because some other devs write the contextual information like the class to the log message.

Having an event prior of a message being logged would enable everyone to add a default context kinda like this:

// Just an example for visualization purposes
public function __invoke(Logger $logger)
{
    $logger->listen(function(MessageTriggered $message) {
        $message->context = [
            "class" => __CLASS__,
            "method" => debug_backtrace()[1]["function"],
            "line" => debug_backtrace()[1]["line"],
            "values" => $message->context,
        ];
    });
}
Log::debug("Hello world", ["name" => "John"];

which would result in something like this:

localhost.DEBUG: Hello world {"class":"App\Foo\Bar","method":"baz","line":1,"values":{"name":"John"}}