Solution found:
- Create a file in
app/Logging/RuntimeFileHandler.php
namespace App\Logging;
use Monolog\Handler\AbstractProcessingHandler;
use Monolog\LogRecord;
class RuntimeFileHandler extends AbstractProcessingHandler
{
protected function write(LogRecord $record): void
{
$filename = $this->getFilename($record);
file_put_contents($filename, (string) $record['formatted'], FILE_APPEND);
}
protected function getFilename(LogRecord $record): string
{
// You can customize this method to generate the desired filename based on the log record.
// Here's an example that uses the 'context' key to store the desired filename:
$filename = $record['context']['filename'] ?? 'default.log';
// Make sure the logs directory exists
$logsDirectory = storage_path('logs/custom');
if (!file_exists($logsDirectory)) {
mkdir($logsDirectory, 0777, true);
}
return $logsDirectory . '/' . $filename;
}
}
\2. Update channels in config/logging.php:
use App\Logging\RuntimeFileHandler;
use Monolog\Formatter\LineFormatter;
return [
// ...
'channels' => [
// ...
'runtime_file' => [
'driver' => 'custom',
'via' => function ($config) {
$handler = new RuntimeFileHandler(Logger::DEBUG);
$handler->setFormatter(new LineFormatter(null, null, true, true));
return new Logger('runtime_file', [$handler]);
},
],
],
];
\3. Call it like this
use Illuminate\Support\Facades\Log;
Log::channel('runtime_file')->info('This is a log message', ['filename' => 'my_log_file.log']);