<?php
namespace app\admin\driver;

use think\log\driver\File;

class Logger extends File
{
    public function save(array $log): bool
    {
        if (!$this->config['json']) {
            $this->config['format'] = '[%s][%s][%s] %s';
        }
        
        $destination = $this->getMasterLogFile();

        $path = dirname($destination);
        !is_dir($path) && mkdir($path, 0755, true);

        $info = [];

        // 日志信息封装
        $time = \DateTime::createFromFormat('0.u00 U', microtime())->setTimezone(new \DateTimeZone(date_default_timezone_get()))->format($this->config['time_format']);

        $request_id = $log['request_id'];
        unset($log['request_id']);

        foreach ($log as $type => $val) {
            $message = [];
            foreach ($val as $msg) {
                if (!is_string($msg)) {
                    $msg = var_export($msg, true);
                }

                $message[] = $this->config['json'] ?
                json_encode(['time' => $time, 'type' => $type, 'request_id' => $request_id, 'msg' => $msg], $this->config['json_options']) :
                sprintf($this->config['format'], $time, $type, $request_id, $msg);
            }

            if (true === $this->config['apart_level'] || in_array($type, $this->config['apart_level'])) {
                // 独立记录的日志级别
                $filename = $this->getApartLevelFile($path, $type);
                $this->write($message, $filename);
                continue;
            }

            $info[$type] = $message;
        }

        if ($info) {
            return $this->write($info, $destination);
        }

        return true;
    }
}