<?php

namespace App\Logging;

use Illuminate\Log\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\LogRecord;

class CustomizeFormatter
{
    /**
     * 自定义给定的日志实例。
     */
    public function __invoke(Logger $logger): void
    {
        foreach ($logger->getHandlers() as $handler) {
            $handler->setFormatter(new LineFormatter(
                "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n",
                'Y-m-d H:i:s',
                true,
                true
            ));

            // 添加更严格的过滤器
            $handler->pushProcessor(function (LogRecord $record): LogRecord {
                // 1. 允许SQL日志
                if (str_contains($record->message, 'sql:')) {
                    return $record;
                }

                // 2. 过滤所有来自vendor目录的日志
                if (isset($record->extra['file']) && str_contains($record->extra['file'], '/vendor/')) {
                    $record->extra['filtered'] = true;
                    return $record;
                }

                // 3. 过滤框架的默认日志通道
                if (in_array($record->channel, [
                    'laravel',
                    'framework',
                    'security',
                    'request',
                    'schedule',
                    'queue',
                ])) {
                    $record->extra['filtered'] = true;
                    return $record;
                }

                // 4. 只允许来自app目录的日志
                if (isset($record->extra['file']) && str_contains($record->extra['file'], '/app/')) {
                    return $record;
                }

                $record->extra['filtered'] = true;
                return $record;
            });
        }
    }
}
