Skip to content

Commit

Permalink
Customise monolog formatter to exclude line breaks
Browse files Browse the repository at this point in the history
  • Loading branch information
martyf committed Dec 5, 2023
1 parent 542f51d commit 37037d7
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/ServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use MityDigital\StatamicLogger\Console\Commands\ListSubscribedEventsCommand;
use MityDigital\StatamicLogger\Http\CP\Controllers\StatamicLoggerController;
use MityDigital\StatamicLogger\Subscribers\StatamicLoggerEventSubscriber;
use MityDigital\StatamicLogger\Support\LoggerFormatter;
use MityDigital\StatamicLogger\Support\StatamicLogger;
use Statamic\Facades\Utility;
use Statamic\Providers\AddonServiceProvider;
Expand Down Expand Up @@ -99,6 +100,7 @@ protected function configureLogger($channel = 'statamic-logger')
'path' => storage_path($path.DIRECTORY_SEPARATOR.$filename),
'level' => 'debug',
'days' => config('statamic-logger.storage.retention', 7),
'tap' => [LoggerFormatter::class],
]);
}
}
Expand Down
23 changes: 23 additions & 0 deletions src/Support/LoggerFormatter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

namespace MityDigital\StatamicLogger\Support;

use Illuminate\Log\Logger;

class LoggerFormatter
{
/**
* Customize the given logger instance.
*/
public function __invoke(Logger $logger): void
{
foreach ($logger->getHandlers() as $handler) {
// get the formatter, and disable inline breaks
$formatter = $handler->getFormatter();
$formatter->allowInlineLineBreaks(false);

// re-set the formatter
$handler->setFormatter($formatter);
}
}
}
40 changes: 40 additions & 0 deletions tests/Support/LoggerFormatterTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use MityDigital\StatamicLogger\Facades\StatamicLogger;
use MityDigital\StatamicLogger\Support\StatamicLoggerReader;

it('stores a log entry with line breaks in a single line', function () {

// set today
$today = Carbon::now()->format('Y-m-d');

// remove the log for today
unlink(storage_path(StatamicLogger::getStoragePath().DIRECTORY_SEPARATOR.StatamicLogger::getStorageFilename().'-'.$today.'.log'));

// log a simple string
Log::channel('statamic-logger')
->info(
json_encode([
'lines' => 'no lines here',
])
);

// log a string with line breaks
Log::channel('statamic-logger')
->info(
json_encode([
'lines' => "a string with\nline breaks",
])
);

// read the last line of the log
$reader = app(StatamicLoggerReader::class);
$data = $reader->paginate($today, 1, 10);

expect($data)
->toHaveCount(2)
->and($data[0])->toContain('{"lines":"a string with\nline breaks"}')
->and($data[1])->toContain('{"lines":"no lines here"}');
});

0 comments on commit 37037d7

Please sign in to comment.