<?php
/**
 * File: ImLog.php
 * Enconding: UTF-8
 * Using: 即时日志记录，不缓存，立马写入文本
 */
namespace app\modules\sys\log;

use Yii;
use yii\helpers\FileHelper;

class ImLog
{
    private static $_instance;

    /**
     * 单个文件大小,KB
     */
    private $_maxFileSize = 10240000;
    /**
     * 目录权限
     */
    private $_dirMode = 0775;

    /**
     * 日志文件路径
     */
    private static $_file;

    public static function instance($strFile = '')
    {
        if (self::$_instance === null) {
            self::$_instance = new ImLog();
        }

        self::$_file = $strFile;
        return self::$_instance;
    }

    private function __construct()
    {

    }

    private function setFile($strFile = '')
    {
        !empty($strFile) || ($strFile = 'im.log');
        self::$_file = Yii::$app->getRuntimePath() . '/logs/' . $strFile;

        $strDirPath = dirname(self::$_file);
        if (!is_dir($strDirPath)) {
            FileHelper::createDirectory($strDirPath, $this->_dirMode, true);
        }

        if (file_exists(self::$_file) && filesize(self::$_file) > $this->_maxFileSize) {
            rename(self::$_file, self::$_file . '.1.' . date('YmdHi'));
        }
    }


    /**
     * 写日志
     * @param string $strTxt 日志内容
     */
    public function Log($strTxt, $blAddPreTime = true)
    {
        $this->setFile(self::$_file);

        if (is_array($strTxt) || is_object($strTxt)) {
            $strTxt = json_encode($strTxt, JSON_UNESCAPED_UNICODE);
        }
        
        if ($blAddPreTime) {
            $strTxt = date('Y-m-d H:i:s ') . $strTxt;
        }

        file_put_contents(self::$_file, $strTxt . PHP_EOL, FILE_APPEND | LOCK_EX);
    }
    
    /**
     * 写入远程网络日志
     * @param unknown $str
     */
    public static function wNet($str)
    {
        (new UdpLog())->write($str, "cdolplat");
    }
}