PHP项目Laravel日志级别如何设定合理

wen PHP项目 5

本文目录导读:

PHP项目Laravel日志级别如何设定合理

  1. 核心配置原则
  2. 环境变量配置
  3. 按业务场景设置级别
  4. 高级日志策略
  5. 性能与安全考量
  6. 日志级别对照表
  7. 推荐配置模板
  8. 日志监控与告警
  9. 总结建议

在Laravel中合理设置日志级别需要根据环境业务需求运维成本来权衡,以下是一套完整的最佳实践指南:

核心配置原则

环境-级别对应关系

// config/logging.php
'channels' => [
    'stack' => [
        'driver' => 'stack',
        'channels' => ['daily'],
        'ignore_exceptions' => false,
    ],
    // 本地开发环境
    'local' => [
        'driver' => 'daily',
        'path' => storage_path('logs/laravel.log'),
        'level' => env('LOG_LEVEL', 'debug'), // 开发环境用debug
        'days' => 7, // 保留7天
    ],
    // 生产环境
    'production' => [
        'driver' => 'daily',
        'path' => storage_path('logs/laravel.log'),
        'level' => env('LOG_LEVEL', 'warning'), // 生产环境用warning
        'days' => 30, // 保留30天
    ],
],

环境变量配置

.env 文件配置

# 本地开发
APP_ENV=local
LOG_CHANNEL=stack
LOG_LEVEL=debug
# 生产环境
APP_ENV=production
LOG_CHANNEL=stack
LOG_LEVEL=warning
LOG_DAILY_DAYS=30

动态切换逻辑

// config/logging.php
return [
    'default' => env('LOG_CHANNEL', 'stack'),
    'channels' => [
        'stack' => [
            'driver' => 'stack',
            'channels' => ['daily'],
        ],
        'daily' => [
            'driver' => 'daily',
            'path' => storage_path('logs/laravel.log'),
            'level' => env('LOG_LEVEL', 'debug'),
            'days' => env('LOG_DAILY_DAYS', 14),
            'permission' => 0644,
        ],
    ],
];

按业务场景设置级别

关键业务日志

// 支付操作 - 必须info级别
Log::info('Payment processed', [
    'order_id' => $orderId,
    'amount' => $amount,
    'user_id' => $userId,
    'transaction_id' => $transactionId
]);
// 用户注册 - error级别记录失败
try {
    $user = User::create($data);
    Log::info('User registered', ['user_id' => $user->id]);
} catch (\Exception $e) {
    Log::error('User registration failed', [
        'error' => $e->getMessage(),
        'email' => $data['email']
    ]);
    throw $e;
}

调试辅助日志

// 仅在debug模式记录
if (config('app.debug')) {
    Log::debug('API Response', [
        'endpoint' => $request->path(),
        'response' => $response
    ]);
}

高级日志策略

分文件记录不同级别

// config/logging.php
'channels' => [
    // 错误日志单独存放
    'error_log' => [
        'driver' => 'daily',
        'path' => storage_path('logs/error.log'),
        'level' => 'error',
        'days' => 30,
    ],
    // 业务日志
    'business' => [
        'driver' => 'daily',
        'path' => storage_path('logs/business.log'),
        'level' => 'info',
        'days' => 30,
    ],
    // 组合通道
    'stack' => [
        'driver' => 'stack',
        'channels' => ['daily', 'error_log', 'business'],
        'ignore_exceptions' => false,
    ],
],

按模块分类

// config/logging.php
'channels' => [
    'order' => [
        'driver' => 'daily',
        'path' => storage_path('logs/order.log'),
        'level' => 'info',
        'days' => 30,
    ],
    'payment' => [
        'driver' => 'daily',
        'path' => storage_path('logs/payment.log'),
        'level' => 'info',
        'days' => 30,
    ],
],
// 使用示例
Log::channel('order')->info('Order created', $orderData);
Log::channel('payment')->error('Payment failed', $errorData);

性能与安全考量

日志消息优化

// ❌ 错误示例 - 记录敏感信息
Log::info('User login', ['password' => $request->password]);
// ✅ 正确示例
Log::info('User login', [
    'user_id' => $user->id,
    'ip' => $request->ip(),
    'user_agent' => substr($request->userAgent(), 0, 200)
]);

大数据量日志优化

// 避免记录大量不必要的数据
Log::debug('List query', ['total' => $items->count()]); // ✅
Log::debug('List query', ['items' => $items->toArray()]); // ❌ 大量数据

异常日志记录模板

// app/Exceptions/Handler.php
public function report(Throwable $exception)
{
    // 忽略404等预期异常
    if ($this->shouldntReport($exception)) {
        return;
    }
    // 记录详细上下文
    Log::error($exception->getMessage(), [
        'exception' => get_class($exception),
        'file' => $exception->getFile(),
        'line' => $exception->getLine(),
        'trace' => $exception->getTraceAsString(),
        'url' => request()->fullUrl(),
        'method' => request()->method(),
        'user' => auth()->id() ?? 'guest'
    ]);
    parent::report($exception);
}

日志级别对照表

级别 使用场景 生产环境
debug 100 开发调试信息 ✗ 不使用
info 200 业务操作记录 ✗ 谨慎使用
notice 250 正常但重要的事件 ✓ 建议使用
warning 300 潜在问题警告 ✓ 建议使用
error 400 错误但不致命 ✓ 必须使用
critical 500 严重错误 ✓ 必须使用
alert 550 需立即处理 ✓ 必须使用
emergency 600 系统不可用 ✓ 必须使用

推荐配置模板

# 生产环境推荐配置
LOG_CHANNEL=stack
LOG_LEVEL=error
LOG_DAILY_DAYS=30
# 测试环境
LOG_CHANNEL=daily
LOG_LEVEL=debug
LOG_DAILY_DAYS=7
# 本地开发
LOG_CHANNEL=daily
LOG_LEVEL=debug
LOG_DAILY_DAYS=7

日志监控与告警

// 自定义日志处理 - 发送到Sentry等工具
'channels' => [
    'sentry' => [
        'driver' => 'monolog',
        'handler' => \Sentry\Monolog\Handler::class,
        'level' => 'error',
    ],
    'stack' => [
        'driver' => 'stack',
        'channels' => ['daily', 'sentry'],
    ],
],

总结建议

  1. 开发环境debug 级别,记录所有信息
  2. 测试环境debug 级别,但减少不必要的数据
  3. 生产环境error 级别,只记录错误和关键业务事件
  4. 关键业务:至少 info 级别,确保可追踪
  5. 安全事件critical 级别,立即报警

最终目标是在保证业务可追踪性的同时,最小化日志量,提升系统性能和可维护性。

抱歉,评论功能暂时关闭!