Laravel 9自定义日志报错:找不到App\Logging\SimpleFormatter类
解决Laravel 9自定义日志中「Target class [App\Logging\SimpleFormatter] does not exist」错误
问题场景
在探索Laravel 9自定义日志功能时,已完成以下操作:
- 在路由中添加日志触发代码:
Route::get('/', function () { // return view('welcome'); Log::channel('abuse')->info('API endpoint abuse', [ 'user_id' => 2 ]); }); - 在
logging.php文件顶部引入use App\Logging\SimpleFormatter; - 创建了
SimpleFormatter类
触发日志时出现如下错误:
[2022-11-18 09:02:31] laravel.EMERGENCY: Unable to create configured logger. Using emergency logger. {"exception":"[object] (Illuminate\Contracts\Container\BindingResolutionException(code: 0): Target class [App\Logging\SimpleFormatter] does not exist. at /Users/Shared/laravel-sanctum-api/vendor/laravel/framework/src/Illuminate/Container/Container.php:877)
[stacktrace]
解决建议
验证类文件路径与命名空间一致性
确保SimpleFormatter.php文件严格位于项目的app/Logging目录下(路径为app/Logging/SimpleFormatter.php),同时类文件内部必须正确声明命名空间:<?php namespace App\Logging; class SimpleFormatter { // 自定义格式化逻辑 }清理自动加载与配置缓存
若路径配置无误仍报错,执行以下命令清理Laravel缓存,确保类自动加载映射更新:composer dump-autoload php artisan config:clear php artisan cache:clear检查日志通道配置引用
确认logging.php中对应日志通道的formatter配置项,正确使用类的完整命名空间或::class语法:// 示例配置 'abuse' => [ 'driver' => 'single', 'path' => storage_path('logs/abuse.log'), 'formatter' => \App\Logging\SimpleFormatter::class, // 或使用字符串形式 // 'formatter' => 'App\Logging\SimpleFormatter', ],
内容的提问来源于stack exchange,提问作者Luqman Ahmad
相关产品推荐
相关产品推荐

