Skip to content

Commit

Permalink
Use symfony filesystem to write logs
Browse files Browse the repository at this point in the history
  • Loading branch information
tuutti committed Oct 14, 2023
1 parent 8f39f1d commit 0de1bf6
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 11 deletions.
5 changes: 5 additions & 0 deletions helfi_api_base.services.yml
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,15 @@ services:
tags:
- { name: event_subscriber }

helfi_api_base.logger_filesystem:
class: Symfony\Component\Filesystem\Filesystem
public: false

helfi_api_base.logger_json:
class: Drupal\helfi_api_base\Logger\JsonLog
arguments:
- '@logger.log_message_parser'
- '@helfi_api_base.logger_filesystem'
- '%helfi_api_base.json_logger_path%'
- '%helfi_api_base.logger_enabled%'
tags:
Expand Down
22 changes: 11 additions & 11 deletions src/Logger/JsonLog.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use Drupal\Core\Logger\RfcLogLevel;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Psr\Log\LoggerInterface;
use Symfony\Component\Filesystem\Filesystem;

/**
* This class allows logging to stdout and stderr.
Expand All @@ -22,28 +23,27 @@ final class JsonLog implements LoggerInterface {
*
* @param \Drupal\Core\Logger\LogMessageParserInterface $parser
* The parser to use when extracting message variables.
* @param \Symfony\Component\Filesystem\Filesystem $filesystem
* The file system.
* @param string $stream
* The output path.
* @param bool $loggerEnabled
* Whether logger is enabled or not.
*/
public function __construct(
private LogMessageParserInterface $parser,
private string $stream,
private bool $loggerEnabled = TRUE
private readonly LogMessageParserInterface $parser,
private readonly Filesystem $filesystem,
private readonly string $stream,
private readonly bool $loggerEnabled = TRUE
) {
}

/**
* Outputs the given entry.
*
* @param array $entry
* The log entry.
* Outputs the messages.
*/
private function output(array $entry) : void {
$stream = fopen($this->stream, 'a');
fwrite($stream, json_encode(['message' => $entry]) . PHP_EOL);
fclose($stream);
private function output(array $message) : void {
$this->filesystem
->appendToFile($this->stream, json_encode(['message' => $message]) . PHP_EOL);
}

/**
Expand Down

0 comments on commit 0de1bf6

Please sign in to comment.