Skip to content

Latest commit

 

History

History
72 lines (57 loc) · 2.83 KB

Monolog_v3.md

File metadata and controls

72 lines (57 loc) · 2.83 KB

Monolog v3.x

Initialize the Formatter

use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Elastic\Monolog\Formatter\ElasticCommonSchemaFormatter;

$logger = new Logger('my_ecs_logger');
$formatter = new ElasticCommonSchemaFormatter();
$handler = new StreamHandler('<path-to-log-dir>/application.json', Logger::INFO);
$handler->setFormatter($formatter);
$logger->pushHandler($handler);

Use ECS Types to enrich your logs

Log Exceptions/Errors/Throwables

In order to enrich a log event with PHP's Throwable's, you need to add to wrap the exception as following.

use Elastic\Types\Error as EcsError;

try {
    //
    // something went wrong
    //
}
catch(\Exception $exception) {
    $logger->error('some meaningful message', ['error' => new EcsError($exception)]);
    // log and do other things ..
}

ECS docs | Service class

Service

The service context enables you to provide more attributes describing your service. Setting a version can help you track system behaviour over time.

use Elastic\Types\Service;

$serviceContext = new Service();
$serviceContext->setName('my-service-005');
$serviceContext->setVersion('1.2.42');

$logger->notice('this message adds service context, nice :)', ['service' => $serviceContext]);

ECS docs | Service class

User

The user context allows you to enrich your log entries with user specific attributes such as user.id or user.name to simplify the discovery of specific log events.

use Elastic\Types\User;

$userContext = new User();
$userContext->setId(12345);
$userContext->setEmail('hello@example.com');

$logger->notice('heya, the context helps you to trace logs more effective', ['user' => $userContext]);

ECS docs | Service class

Please be aware that a method User::setHash is available, if you want to obfuscate user.id, user.name, etc.

Tracing

You can add a tracing context to every log message by leveraging the trace key in contex to pass a trace Id.

use Elastic\Types\Tracing;

$tracingContext = new Tracing('<trace-id>', '<transaction-id>');

$logger->notice('I am a log message with a trace id, so you can do awesome things in the Logs UI', ['tracing' => $tracingContext]);

ECS docs | Tracing class