nostadt/psr3-log-context

1.0.1 2023-10-15 11:14 UTC

This package is auto-updated.

Last update: 2024-11-06 21:21:04 UTC


README

CI Process packagist.org

Preamble

Especially for larger projects logging is essential. You do want to have all the data you need when looking in the past. Nothing is worse than having a serious issue on the production system but lacking of helpful context information. This small package makes it easy to log in a structured manner without cluttering your code.

Available classes and interface

Further link/s

Examples

Use LogContext::createFromException

This is the recommended way when dealing with Exceptions, unless they implement LogContextConvertibleInterface.

<?php

use \Nostadt\Psr3LogContext\LogContext;

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

Use LogContextConvertibleInterface

This is the recommend way, because it truly simplifies creating the log-context array.

<?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());

Merge multiple LogContexts

With previous User-class in mind we can merge LogContext-objects.

<?php

use \Nostadt\Psr3LogContext\LogContext;

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

Create a LogContext from the scratch

This can be used in situations in which LogContext is not available.

<?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());

Development

Requirements:

If you start fresh, execute:

make init
make start

If you want to run code-quality checks, execute:

make test
make lint

If you are done working, execute:

make stop

If you want to continue working, execute:

make start

If you want to clean up the system, execute:

make clean