tixelrocks/laravel-safe-logger

Laravel Logger 的小型包装器,防止其崩溃

0.3 2024-09-16 14:17 UTC

This package is auto-updated.

Last update: 2024-09-16 14:18:55 UTC


README

一个安全的 Laravel 日志器,永远不会使您的应用程序崩溃

介绍

此仓库基于我们失败的 Laravel 框架 PR: laravel/framework#45604

因为我们认为它非常有用,所以我们将其提取为包。

想法非常简单,可以用一句话概括

日志功能永远不会使您的应用程序崩溃

或者换句话说

在任何情况下,绝对不能使日志功能使您的应用程序崩溃

当事情出错时,人们会依赖于日志,所以您最不希望发生的事情就是因为日志而使事情变得更糟。

例如,尝试使 JavaScript 的 console.log 崩溃(祝你好运!)

console.log('plain message')
// plain message
console.log('plain message', 123, [])
// plain message 123 []

您可以发送任何内容,它都会正常工作。因为当事情出错时,您不想担心日志会使事情变得更糟。

现在回到 Laravel,使用 Log 门面时,很容易打破整个应用程序

Log::emergency('Something bad happened!', false);
Illuminate\Log\LogManager::emergency(): Argument #2 ($context) must be of type array, bool given, called in vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php on line 338 in vendor/psy/psysh/src/Exception/TypeErrorException.php on line 53.

如果这看起来太人为,这里有一个现实世界的例子

try {
    $details = $api->request(); // $api is some kind of a third-party SDK
} catch (ClientException $e) {
    // $e->getResponse() might have a nice JSON error message but might have a CDN's HTML error or something else
    Log::emergency("Oh no, we got a failed API request!", json_decode($e->getResponse()->getContent()));
}

是的 - 开发者可以小心行事,始终传递正确的参数,字符串和数组,但我们真的想对日志记录器小心吗?这有意义吗?

如果您参考 PSR 文档: https://www.php-fig.org/psr/psr-3/

1.3 Context
...The array can contain anything. Implementors MUST ensure they treat context data with as much lenience as possible. A given value in the context MUST NOT throw an exception nor raise any php error, warning or notice.

它实际上提到我们永远不应该抛出任何错误或异常,应该尽可能宽容。

安装

$ composer require tixelrocks/laravel-safe-logger

就是这样!现在我们可以做一些“古怪”的事情,比如

Log::emergency("Hello", $results, 'Another message');

当然,我们不必这么做。但能够不担心 Log 会使您的应用程序崩溃是很棒的。