Laravel日志系统支持多驱动与自定义频道,可在config/logging.php中配置payment等独立频道写入指定文件,通过Log::channel('payment')使用,支持动态创建临时频道如Log::build()用于调试,结合环境配置实现多目标日志记录。

在 Laravel 中,日志系统非常灵活,支持多种日志驱动,并允许你自定义日志频道来满足不同场景的需求。你可以将特定类型的日志写入独立文件、发送到 Slack、Telegram 或通过 Monolog 发送到外部服务。
配置自定义日志频道
Laravel 的日志配置位于 config/logging.php 文件中。你可以在这里定义新的日志频道。例如,创建一个专门记录支付相关日志的频道:
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['single', 'payment'],
'ignore_exceptions' => false,
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
],
'payment' => [
'driver' => 'single',
'path' => storage_path('logs/payment.log'),
'level' => 'info',
],
],
登录后复制
上面添加了一个名为 payment 的频道,它会将日志写入 storage/logs/payment.log 文件。
使用自定义频道写入日志
在代码中,你可以通过 Log 门面指定使用哪个频道:
use Illuminate\Support\Facades\Log;
// 写入默认日志
Log::info('用户登录成功');
// 写入 payment 频道
Log::channel('payment')->info('支付请求已发起', [
'order_id' => '20240510001',
'amount' => 99.9
]);
// 也可以直接调用
Log::build([
'driver' => 'single',
'path' => storage_path('logs/debug_api.log')
])->info('API调试信息');
登录后复制
动态创建临时频道
如果你需要临时输出日志到某个特定文件(比如调试接口),可以使用 Log::build() 动态创建频道:
例如,在控制器中快速记录 API 请求数据:
版权声明:除非特别标注,否则均为本站原创文章,转载时请以链接形式注明文章出处。
还木有评论哦,快来抢沙发吧~