如何在Laravel Lumen中配置多日志通道实现分文件记日志?
Hey there! I’ve tackled this exact issue before when working with Lumen—since it doesn’t ship with the config/logging.php file out of the box like Laravel does, we need to set it up manually to get multiple log channels writing to separate files. Here’s how to do it:
Step 1: Create the Logging Config File
First, if you don’t already have a config directory in your Lumen project root, create one. Then, inside that directory, make a new file named logging.php with the following content:
<?php return [ // Optional: Set a default channel if you need one 'default' => env('LOG_CHANNEL', 'case1'), 'channels' => [ 'case1' => [ 'driver' => 'single', // Use 'daily' instead if you want rotating logs 'path' => storage_path('logs/case1.log'), 'level' => 'debug', // Capture all logs from debug level and above ], 'case2' => [ 'driver' => 'single', 'path' => storage_path('logs/case2.log'), 'level' => 'debug', ], ], ];
Step 2: Load the Config in Bootstrap
Next, we need to tell Lumen to recognize this new config file. Open bootstrap/app.php and add this line somewhere near the top (right after the $app is initialized):
$app->configure('logging');
Also, make sure Facades are enabled—look for this line and uncomment it if it’s commented out:
$app->withFacades();
This lets you use the Log facade exactly like you planned (Log::channel('case1')->info('msg1')).
Step 3: Test Your Setup
Now you can use the channels just as you wanted:
Log::channel('case1')->info('msg1');will write tostorage/logs/case1.logLog::channel('case2')->info('msg2');will write tostorage/logs/case2.log
Bonus: Advanced Customization (If Needed)
If you need more control over Monolog (like custom log formatters or processors), you can extend channels directly in bootstrap/app.php. For example:
$app->configureMonologUsing(function ($monolog) use ($app) { // Add a custom handler for case1 with a formatted output $case1Handler = new \Monolog\Handler\StreamHandler(storage_path('logs/case1.log'), \Monolog\Logger::DEBUG); $case1Handler->setFormatter(new \Monolog\Formatter\LineFormatter( '[%datetime%] %channel%.%level_name%: %message% %context% %extra%' . PHP_EOL, null, false, true )); $monolog->pushHandler($case1Handler); // Register a named channel for case2 $app->log->extend('case2', function ($app) { $handler = new \Monolog\Handler\StreamHandler(storage_path('logs/case2.log'), \Monolog\Logger::DEBUG); return new \Monolog\Logger('case2', [$handler]); }); });
Just make sure this code comes before the $app->run(); line.
Quick Heads-Up
Don’t forget to check that your storage/logs directory has proper write permissions for your web server or CLI user—otherwise, the log files won’t be created.
内容的提问来源于stack exchange,提问作者Fractalf

