Skip to content

1.0.0 GA #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jan 2, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ composer require elastic/ecs-logging
```

## Examples and Usage
* [Monolog](https://github.com/elastic/ecs-logging-php/blob/master/docs/Monolog/README.md)
* [Monolog v2](https://github.com/elastic/ecs-logging-php/blob/master/docs/Monolog_v2.md)

## Library Support
* Currently only [Monolog:2.*](https://github.com/Seldaek/monolog) is supported.
Expand Down
27 changes: 0 additions & 27 deletions docs/Monolog/README.md

This file was deleted.

72 changes: 72 additions & 0 deletions docs/Monolog_v2.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# Monolog v2.x

## Initialize the Formatter
```php
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Elastic\Monolog\v2\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 Excpetions/Errors/Throwables
In order to enrich a log event with PHP's [`Throwable`](https://www.php.net/manual/en/class.throwable.php)'s, you need to add to wrap the exception as following.
```php
use Elastic\Types\Error as EcsError;

try {
//
// something went wrong
//
}
catch(Excpetion $exception) {
$logger->error('some meaningful message', ['error' => new EcsError($exception)]);
// log and do other things ..
}
```
ECS [docs](https://www.elastic.co/guide/en/ecs/current/ecs-error.html) | Service [class](https://github.com/elastic/ecs-logging-php/blob/master/src/Elastic/Types/Error.php)

### Service
The service context enables you to provide more attributes describing your service. Setting a version can help you track system behaviour over time.
```php
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](https://www.elastic.co/guide/en/ecs/current/ecs-service.html) | Service [class](https://github.com/elastic/ecs-logging-php/blob/master/src/Elastic/Types/Service.php)

### 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.
```php
use Elastic\Types\User;

$userContext = new User();
$userContext->setId(12345);
$userContext->setEmail('[email protected]');

$logger->notice('heya, the context helps you to trace logs more effective', ['user' => $userContext]);
```
ECS [docs](https://www.elastic.co/guide/en/ecs/current/ecs-user.html) | Service [class](https://github.com/elastic/ecs-logging-php/blob/master/src/Elastic/Types/User.php)

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.
```php
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](https://www.elastic.co/guide/en/ecs/current/ecs-tracing.html) | Tracing [class](https://github.com/elastic/ecs-logging-php/blob/master/src/Elastic/Types/Tracing.php)
5 changes: 3 additions & 2 deletions phpcs.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?xml version="1.0"?>
<ruleset name="Elasticsearch-PHP">
<rule ref="PSR2">
<ruleset name="ecs-logging-php">
<rule ref="PSR12">
<exclude name="Generic.Files.LineLength.TooLong"/>
<exclude name="PSR12.Files.ImportStatement.LeadingSlash"/>
</rule>
</ruleset>
Original file line number Diff line number Diff line change
@@ -1,22 +1,25 @@
<?php declare(strict_types=1);
<?php

declare(strict_types=1);

// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information

namespace Elastic\Monolog\Formatter;
namespace Elastic\Monolog\v2\Formatter;

use Monolog\Formatter\NormalizerFormatter;

use Elastic\Types\{Tracing, User, Service};
use Throwable;

/**
* Serializes a log message to the Elastic Common Schema (ECS)
*
* @version ECS v1.2.0
* @version Monolog v2.x
* @version ECS v1.x
*
* @see https://www.elastic.co/guide/en/ecs/1.2/ecs-log.html
* @see Elastic\Monolog\Formatter\ElasticCommonSchemaFormatterTest
* @see https://www.elastic.co/guide/en/ecs/1.4/ecs-log.html
* @see Elastic\Monolog\v2\Formatter\ElasticCommonSchemaFormatterTest
*
* @author Philip Krauss <[email protected]>
*/
Expand Down Expand Up @@ -59,37 +62,43 @@ public function format(array $record): string
],
];

// Add Exception
if (isset($record['context']['throwable']) === true) {
if (isset($record['message']) === false) {
$message['message'] = $record['context']['throwable']['error']['message'];
}
$message['error'] = $record['context']['throwable']['error'];
$message['log'] = array_merge($message['log'], $record['context']['throwable']['log']);
unset($record['context']['throwable']);
}

// Add Tracing Context
if (isset($record['context']['trace']) === true) {
$message['trace'] = ['id' => trim($record['context']['trace'])];
unset($record['context']['trace']);
// Add Error Context
if (isset($record['context']['error']['Elastic\Types\Error']) === true) {
$message['error'] = $record['context']['error']['Elastic\Types\Error']['error'];
$message['log'] = array_merge($message['log'], $record['context']['error']['Elastic\Types\Error']['log']);

if (isset($record['context']['transaction']) === true) {
$message['transaction'] = ['id' => trim($record['context']['transaction'])];
unset($record['context']['transaction']);
}
$record['message'] ?? $message['error']['message'];
unset($record['context']['error']);
}

// Add Log Message
if (isset($record['message']) === true) {
$message['message'] = $record['message'];
}

// Add Tracing Context
if (isset($record['context']['tracing']['Elastic\Types\Tracing']) === true) {
$message += $record['context']['tracing']['Elastic\Types\Tracing'];
unset($record['context']['tracing']);
}

// Add Service Context
if (isset($record['context']['service']['Elastic\Types\Service']) === true) {
$message += $record['context']['service']['Elastic\Types\Service'];
unset($record['context']['service']);
}

// Add User Context
if (isset($record['context']['user']['Elastic\Types\User']) === true) {
$message += $record['context']['user']['Elastic\Types\User'];
unset($record['context']['user']);
}

// Add ECS Labels
if (empty($record['context']) === false) {
$message['labels'] = [];
foreach ($record['context'] as $key => $val) {
$message['labels'][str_replace(['.', ' '], '_', trim($key))] = $val;
$message['labels'][str_replace(['.', ' ', '*', '\\'], '_', trim($key))] = $val;
}
}

Expand All @@ -100,33 +109,4 @@ public function format(array $record): string

return $this->toJson($message) . "\n";
}

/**
* Normalize Exception and return ECS compliant formart
*
* @param Throwable $e
* @param int $depth, Def: 0
*
* @return array
*/
protected function normalizeException(Throwable $e, int $depth = 0)
{
$normalized = parent::normalizeException($e, $depth);
return [
'error' => [
'type' => $normalized['class'],
'message' => $normalized['message'],
'code' => $normalized['code'],
'stack_trace' => explode(PHP_EOL, $e->getTraceAsString()),
],
'log' => [
'origin' => [
'file' => [
'name' => $e->getFile(),
'line' => $e->getLine(),
],
],
],
];
}
}
31 changes: 31 additions & 0 deletions src/Elastic/Types/BaseType.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

declare(strict_types=1);

// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information

namespace Elastic\Types;

class BaseType
{

/**
* Get the Popo as array
*
* @return array
*/
public function toArray(): array
{
return $this->jsonSerialize();
}

/**
* Serialize self to JSON
*/
public function __toString(): string
{
return json_encode($this);
}
}
61 changes: 61 additions & 0 deletions src/Elastic/Types/Error.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php

declare(strict_types=1);

// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information

namespace Elastic\Types;

use JsonSerializable;
use Throwable;

/**
* Serializes to ECS Error
*
* @version v1.x
*
* @see https://www.elastic.co/guide/en/ecs/current/ecs-error.html
*
* @author Philip Krauss <[email protected]>
*/
class Error extends BaseType implements JsonSerializable
{

/**
* @var array
*/
private $data;

/**
* @param Throwable $throwable
*/
public function __construct(Throwable $throwable)
{
$this->data = [
'error' => [
'type' => get_class($throwable),
'message' => $throwable->getMessage(),
'code' => $throwable->getCode(),
'stack_trace' => explode(PHP_EOL, $throwable->getTraceAsString()),
],
'log' => [
'origin' => [
'file' => [
'name' => $throwable->getFile(),
'line' => $throwable->getLine(),
],
],
],
];
}

/**
* @return array
*/
public function jsonSerialize()
{
return $this->data;
}
}
Loading