<?php

namespace Lib;


/**
 * 日志文件
 * @author:dc
 * @time 2023/3/14 10:26
 * Class Log
 * @package Lib
 */
class Log {


    /**
     * @var array
     */
    public array $filename = [];

    /**
     * @var array
     */
    public array $message = [];

    /**
     * @var self
     */
    private static self $instance;

    /**
     * Log constructor.
     */
    public function __construct()
    {
        $this->setFilename();
    }

    /**
     * 追加日志内容
     * @param string $message
     * @author:dc
     * @time 2023/3/14 10:45
     */
    public static function append(string $message, $filename = null){

        if($filename){
            self::getInstance()->setFilename($filename);
        }

        self::getInstance()->message[$filename ? md5($filename) : 'default'][] = date('Y-m-d H:i:s  ').$message;

    }


    /**
     * @return Log
     */
    public static function getInstance(): Log
    {
        if (empty(static::$instance)){
            static::$instance = new Log();
        }

        return self::$instance;
    }

    /**
     * 设置日志文件
     * @param $filename
     * @author:dc
     * @time 2023/3/14 11:11
     */
    private function setFilename($filename=null){
        if($filename){
            $this->filename[md5($filename)] = $filename;
        }else{
            $this->filename['default'] = $filename = LOG_PATH.'/'.app()->nowDate().'.error.log';
        }

        // 创建目录
        if(!is_dir(dirname($filename))){
            @mkdir(dirname($filename),0755,true);
        }

    }

    /**
     * 写入日志
     * @author:dc
     * @time 2023/3/14 10:45
     */
    public function write(){

        foreach ($this->filename as $key=>$fn){
            if(!empty($this->message[$key])){
                $fo = @fopen($fn,'a');
                if($fo){
                    foreach ($this->message[$key] as &$log){
                        @fwrite($fo,$log.PHP_EOL);
                    }
                    @fclose($fo);
                }

                $log = null;
                unset($log);

                $this->message[$key] = null;
                unset($this->message[$key]);
            }

        }

    }

}