Skip to content

Commit

Permalink
Format syslog messages
Browse files Browse the repository at this point in the history
The GelfMessageToStringFormatter is used from other steup projects. It logs in
json format to syslog.
  • Loading branch information
MKodde committed Jan 14, 2020
1 parent 9d62794 commit 7bf2ec5
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 0 deletions.
1 change: 1 addition & 0 deletions config/packages/prod/monolog.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ monolog:
type: syslog
ident: stepup-azure-mfa
facility: user
formatter: monolog.formatter.gelf_message
console:
type: console
process_psr_3_messages: false
3 changes: 3 additions & 0 deletions config/services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,6 @@ services:
$locales: '%locales%'
$supportUrl: '%support_url%'
$supportEmail: '%support_email%'

Surfnet\AzureMfa\Infrastructure\Monolog\Formatter\GelfMessageToStringFormatter:
alias: monolog.formatter.gelf_message
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?php declare(strict_types = 1);

/**
* Copyright 2020 SURFnet B.V.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Surfnet\AzureMfa\Infrastructure\Monolog\Formatter;


use Monolog\Formatter\FormatterInterface;
use Monolog\Formatter\GelfMessageFormatter;

class GelfMessageToStringFormatter implements FormatterInterface
{
/**
* @var GelfMessageFormatter
*/
private $formatter;

/**
* @param GelfMessageFormatter $formatter
*/
public function __construct(GelfMessageFormatter $formatter)
{
$this->formatter = $formatter;
}

/**
* {@inheritdoc} the gelf message is an array which cannot be logged into a single line
* By jsonencoding the message we can write it on a single line
*/
public function format(array $record): string
{
$message = $this->formatter->format($record);

// we need to keep the last new line, otherwise everything is appended on the same line :)
$message->setFullMessage(str_replace("\n", ', ', $message->getFullMessage()) . "\n");

return json_encode($message->toArray());
}

/**
* Formats a set of log records.
*
* @param array $records A set of records to format
* @return mixed The formatted set of records
*/
public function formatBatch(array $records): array
{
return array_map([$this, 'format'], $records);
}
}

0 comments on commit 7bf2ec5

Please sign in to comment.