Skip to content
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

Async log sending #15

Merged
merged 2 commits into from
Mar 20, 2024
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
8 changes: 6 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
# Datadog Monolog integration

Monolog Handler to forward logs to Datadog using async requests.
Uses pcntl for async logging, will automatically fall back to non async requests if pcntl is not available.

## Requirements
- PHP 8.1+
- PHP Curl

## Optional
- php-pcntl ( required for async logging )

## Installation

```shell
Expand Down Expand Up @@ -35,8 +39,8 @@ $datadogLogs = new DatadogHandler($apiKey, $host, $attributes, Monolog\Level::In
$logger->pushHandler($datadogLogs);

$logger->info('i am an info');
$logger->warning('i am a warning..');
$logger->error('i am an error ');
$logger->warning('i am a warning');
$logger->error('i am an error');
$logger->notice('i am a notice');
$logger->emergency('i am an emergency');
```
7 changes: 6 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@
"monolog/monolog": "^3.0",
"guzzlehttp/guzzle": "^7.5"
},
"suggest": {
"ext-pcntl": "*"
},
"autoload": {
"psr-4": {
"sgoettsch\\MonologDatadog\\": "src/Monolog"
Expand All @@ -27,6 +30,8 @@
"phpunit/phpunit": "^10.0"
},
"scripts": {
"test": "php vendor/bin/phpunit --fail-on-deprecation"
"test": "php vendor/bin/phpunit --fail-on-deprecation",
"codeStyle:fix": "docker run --rm -v %CD%\\\\:/data cytopia/php-cs-fixer fix .",
"code:check": "docker run --rm --mount type=bind,src=%CD%\\\\,target=/app ghcr.io/sgoettsch/docker-phpstan:latest-php8.1 analyse /app"
}
}
61 changes: 58 additions & 3 deletions src/Monolog/Handler/DatadogHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
use Monolog\Formatter\JsonFormatter;
use Monolog\Handler\MissingExtensionException;
use Monolog\Level;
use Monolog\Logger;
use Monolog\Handler\AbstractProcessingHandler;
use Monolog\Formatter\FormatterInterface;
use Monolog\LogRecord;
Expand All @@ -24,22 +23,28 @@ class DatadogHandler extends AbstractProcessingHandler
/** @var array Datadog optional attributes */
private array $attributes;

/** @var Client to overwrite the default client */
private Client $client;

/** @var bool use async sending, will always fall back to non async mode if async not available */
private bool $useAsync = false;

/**
* @param string $apiKey Datadog API-Key
* @param string $host Datadog API host
* @param array $attributes Datadog optional attributes
* @param Level $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* @param bool $async Use async sending, will always fall back to non async mode if async not available
* @throws MissingExtensionException
*/
public function __construct(
string $apiKey,
string $host = 'https://http-intake.logs.datadoghq.com',
array $attributes = [],
Level $level = Level::Debug,
bool $bubble = true
bool $bubble = true,
bool $async = false
) {
if (!extension_loaded('curl')) {
throw new MissingExtensionException('The curl extension is needed to use the DatadogHandler');
Expand All @@ -54,6 +59,7 @@ public function __construct(
$this->apiKey = $apiKey;
$this->host = $host;
$this->attributes = $attributes;
$this->useAsync = $async;
}

public function setClient(Client $client): void
Expand Down Expand Up @@ -111,6 +117,12 @@ protected function send(LogRecord $record): void
$client = $this->client ?? new Client();
$request = new Request('POST', $url, $headers, json_encode($payLoad, JSON_THROW_ON_ERROR));

if ($this->canAsync()) {
if ($this->fireAndForget($client, $request)) {
return;
}
}

$promise = $client->sendAsync($request);
$promise->wait();
}
Expand Down Expand Up @@ -144,7 +156,7 @@ protected function getService(LogRecord $record): string
*/
protected function getHostname(): string
{
return $this->attributes['hostname'] ?? $_SERVER['SERVER_NAME'];
return $this->attributes['hostname'] ?? $_SERVER['SERVER_NAME'] ?? '';
}

/**
Expand Down Expand Up @@ -192,4 +204,47 @@ protected function getDefaultFormatter(): FormatterInterface
{
return new JsonFormatter();
}

private function canAsync(): bool
{
if (!function_exists('pcntl_fork')) {
return false;
}

return $this->useAsync;
}

private function fireAndForget(Client $client, Request $request): bool
{
if (!function_exists('pcntl_fork')) {
return false;
}

$pid = pcntl_fork();

if ($pid === -1) {
return false;
} elseif ($pid === 0) {
return true;
} else {
register_shutdown_function(function ($pid) {
if (!function_exists('pcntl_waitpid')) {
return false;
}

// keep the process alive until main finishes, this does not end any shared connections like mysql
pcntl_waitpid($pid, $status);

return true;
}, $pid);
$this->sendRequest($client, $request);
exit();
}
}

private function sendRequest(Client $client, Request $request): void
{
$promise = $client->sendAsync($request);
$promise->wait();
}
}
3 changes: 2 additions & 1 deletion tests/LogTest.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<?php
declare(strict_types = 1);

declare(strict_types=1);

namespace sgoettsch\MonologDatadogTest;

Expand Down