timdev/timdev-log

针对PHP的(非常)有观点的结构化日志。可能不适合你。

0.1.2 2021-09-26 22:30 UTC

This package is auto-updated.

Last update: 2024-08-27 04:24:47 UTC


README

针对PHP的(非常)有观点的结构化、日志。可能不适合你。

目标

这个包代表了我对PHP应用程序日志记录(坦白说,正在不断演变)的方法。它将 timdev/stack-loggermonolog 组合,生成一种独特的 ndjson 日志风格。

主要目标是减少在设置PHP应用程序日志记录时需要决定或记住的事情的数量。因此,配置旋钮被有意减少。

日志记录器

日志记录器扩展了 timdev/stack-logger 的 MonologStackLogger,提供一个带有仅三个标量参数的静态工厂(其中只有一个参数是必需的)。它还提供了一些便利方法来帮助记录应用程序事件和异常。仅此而已。

包含的中间件

StackLogger 提供了一些很好的可能性。特别是在基于中间件的Web应用程序中,在请求早期向日志记录器实例添加一些持久上下文可能很方便,这样它就会包含在所有后续的日志调用中。

这个库包括我在Web应用程序项目中使用的几个 StackLogger 兼容的 PSR-15 中间件。

TimDev\Log\Middleware\LogRequestAttributes

从PSR7 ServerRequest中提取请求属性,并将它们作为上下文添加到日志记录器中。

示例

use Psr\Http\Message\ServerRequestInterface as SRI;
use TimDev\Log\Middleware\LogRequestAttributes;

$middleware = new LogRequestAttributes(
    // A StackLogger instance
    $logger,
    // map of context-key => request-attribute name | callable
    [
        // Extract 'user_id' attribute from request, and set the 'uid' 
        // context value on the logger.
        'uid' => 'user_id',
        
        // The above is a shortcut for:
        'uid2' => fn(SRI $req) => $req->getAttribute('user_id'),
        
        // If you want other data from the request, you can use the same pattern
        // to get it. For example:
        'ref' => fn(SRI $req) => $req->getHeader('Referer')[0] ?? null
    ];  
);

中间件不会为 null 值设置上下文键。

有关更多示例用法,请参阅 测试

TimDev\Log\Middleware\DevelopmentRedirect

这个中间件从重定向响应中删除 Location 头,并用包含 meta-refresh 标签的基本HTML文档替换主体。

如果你使用类似 Monolog 的 BrowserConsoleHandler 这样的工具,它依赖于向浏览器发出javascript以执行并将日志消息推送到浏览器控制台,这将很有用。

示例

use Psr\Http\Message\ServerRequestInterface as SRI;
use TimDev\Log\Middleware\DevelopmentRedirect;

// Seconds to delay before refreshing. Default is zero.
$delaySeconds = 2;
$middleware = new DevelopmentRedirect($delaySeconds);

通常应该在管道中 早期 添加此中间件,因为它只接触响应,并且你希望响应修改发生在最后或接近最后。在我的项目中,我通常这样做

// ErrorHandler is the outermost middleware.
$app->pipe(ErrorHandler::class);
// If we're adding it, the DR middlware is the second outer-most.
if (getenv('APP_ENV') === 'development'){
    $app->pipe(new DevelopmentRedirect(1));
}
// ... all the rest of my middlewares.

框架集成

Mezzio

迄今为止,我已经使用此设置与基于 Mezzio 的应用程序。

此包提供了一个 ConfigProvider 和一个 LoggerFactory

要将此日志记录器设置到您的 mezzio 项目中,只需在您的配置中添加 ConfigProvider,您就会在容器中获得一个日志记录器

$logger = $container->get(\TimDev\Log\Logger::class);

// It's a PSR3 logger!
$logger->info('I can do PSR3 things ...');

// It's a StackLogger!
$childLogger = $logger->withContext(['some' => 'context']);
$childLogger->debug('foo');

// You can throw exceptions at it!
$ex = new \LogicException('Ya dun goofed!');
$logger->exception($ex);

// etc

您可以在任何适当的 config/autoload/*.php 文件中配置日志记录器。一个完整的配置可能看起来像这样

config/autoload/timdev_log.local.php

return [
    'timdev' => [
        'log' => [
            'name'    => 'my-app',              // default: 'app'
            'logfile' => 'data/logs/app.log'    // default: 'php://stdout'
            'enable_browser_console' => true,   // default: false
            'dev_redir_delay_seconds' => 2      // default: 0
        ]       
    ]
];