How to setup greylog with wonolog?
juslintek opened this issue · 4 comments
Hi, how to setup wonolog with greylog?
Howdy.
Basically you just need to use the gelf-php-package.
Have a look at: https://inpsyde.com/en/log-management-with-graylog/?noredirect=en_US :)
I'm currently setting up Wonolog with GrayLog but I need to pass a custom field (an auth token) to the Gelf JSON payload aka an additional
These could be passed as the 3rd array $context
argument of a Gelf\Logger
By default Wonolog initializes a Monolog\Logger using one parameter.
What would be the way to initialize the default context of a GelfHandler?
Good morning.
Internally we're using the Monolog\Logger
. The linked Gelf\Logger
is not used in Wonolog by default.
It is possible to use the Inpsyde\Wonolog\Channels::ACTION_LOGGER
-hook, to replace the Logger, but it is currently not supported to use a Psr\Log\LoggerInterface
here. Our code relies on Logger::getName()
which is specific to Monolog.
When looking at the Gelf\Message::$additionals
, i can see, that they are just added via $message['_'.$key]
in Message::toArray()
.
What i would suggest is, that you bootstrap Wonolog with build in the GelfHandler and adding a processor to add the key:
<?php
use Monolog\Handler\GelfHandler;
use Monolog\Processor ProcessorInterface;
$publisher = Gelf\Publisher();
$handler = new GelfHandler($publisher);
$handler->pushProcessor(new class implements ProcessorInterface {
public function __invoke(array $record)
{
$record['_your-token'] = '....';
return $record;
}
});
Wonolog\bootstrap($handler);
Wonolog v1 does not allow to use custom Loggers, but only custom Handlers and/or Formatters.
Wonolog v2 will have that possibility. As for v1, the solution provided by @Chrico is one way to go.
Alternatively, you could extend the GelfMessageFormatter
like:
class MyFormatter extends \Monolog\Formatter\GelfMessageFormatter
{
private $token;
public function __construct(
string $token,
?string $systemName = null,
?string $extraPrefix = null,
string $contextPrefix = 'ctxt_',
?int $maxLength = null
) {
$this->token = $token;
parent::__construct($systemName, $extraPrefix, $contextPrefix, $maxLength);
}
public function format(array $record): \Gelf\Message
{
$message = parent::format($record);
return $message->setAdditional('token', $this->token);
}
}
and then for Wonolog:
$handler = new GelfHandler(new Gelf\Publisher());
$handler->setFormatter(new MyFormatter('...token...'));
Wonolog\bootstrap($handler);