nostadt/psr3-log-context

日志上下文变得简单

1.0.1 2023-10-15 11:14 UTC

This package is auto-updated.

Last update: 2024-09-06 20:55:12 UTC


README

CI Process packagist.org

序言

特别适用于大型项目,日志记录至关重要。您确实希望在回顾过去时拥有所需的所有数据。没有比在生产系统中遇到严重问题但缺乏有用的上下文信息更糟糕的事情了。这个小包使您能够以结构化的方式轻松记录,而不会使您的代码杂乱无章。

可用的类和接口

更多链接

示例

使用 LogContext::createFromException

这是处理异常时的推荐方式,除非它们实现了 LogContextConvertibleInterface

<?php

use \Nostadt\Psr3LogContext\LogContext;

try {
    doSomething();
} catch (\Exception $exception) {
    $this->logger->warning(
        $exception->getMessage(),
        LogContext::createFromException($exception)->toArray()
    );
}

使用 LogContextConvertibleInterface

这是推荐的方式,因为它真正简化了创建日志上下文数组的过程。

<?php

class User implements \Nostadt\Psr3LogContext\LogContextConvertibleInterface
{
    public int $id;
    public bool $activated;
    public string $name;

    public function asLogContext(): \Nostadt\Psr3LogContext\LogContext
    {
        return new \Nostadt\Psr3LogContext\LogContext(
            new \Nostadt\Psr3LogContext\ValueObject\LogData('user_id', (string)$this->id),
            new \Nostadt\Psr3LogContext\ValueObject\LogData('user_activated', $this->activated ? 'true' : 'false'),
            new \Nostadt\Psr3LogContext\ValueObject\LogData('user_name', $this->name),
        );
    }
}

$user = new User();
$user->id = 1;
$user->activated = true;
$user->name = 'John Doe';

$logger->warning('My Message', $user->asLogContext()->toArray());

合并多个 LogContexts

考虑到之前的 User-类,我们可以合并 LogContext-对象。

<?php

use \Nostadt\Psr3LogContext\LogContext;

try {
    registerUser($user);
} catch (\Exception $exception) {
    $this->logger->warning(
        $exception->getMessage(),
        LogContext::createFromException($exception)->mergeLogContext($user->asLogContext())->toArray()
    );
}

从头创建 LogContext

这可以在没有 LogContext 的情况下使用。

<?php

$logContext = new \Nostadt\Psr3LogContext\LogContext(
    new \Nostadt\Psr3LogContext\ValueObject\LogData('user_uid', '1'),
    new \Nostadt\Psr3LogContext\ValueObject\LogData('user_activated', 'true'),
    new \Nostadt\Psr3LogContext\ValueObject\LogData('user_name', 'John Doe'),
);

$logger->warning('My Message', $logContext->toArray());

开发

要求

如果您从头开始,请执行

make init
make start

如果您想运行代码质量检查,请执行

make test
make lint

如果您完成工作,请执行

make stop

如果您想继续工作,请执行

make start

如果您想清理系统,请执行

make clean