構建本身的PHP框架(日誌)

完整項目地址:https://github.com/Evai/Aier

 

日誌在程序開發中有着十分重要的做用,幫助開發者更快的找到程序錯誤並即時處理。下面製做一個很是簡單的記錄日誌類。

在 services 目錄下建立Log.php :php

 

<?php

date_default_timezone_set('PRC');
/**
 * Class Log
 */
class Log
{
    public $path = BASE_PATH . '/log';

    /**
     * Log constructor.
     * @param $msg
     * @param string $path
     */
    public function __construct($msg, $path = '')
    {
        //日誌路徑
        $path = $path ? $path : $this->path;
        //天天生成一個日誌文件
        $filePath = $path . '/' . date('Y-m-d');

        if (!is_dir($filePath)) mkdir($filePath, 0777, true);
        //每小時生成一個日誌文件,防止日誌文件過大
        $nowTime = date('H');
        //文件名
        $fileName = $filePath . '/' . $nowTime . '.log';
        //記錄日誌時間
        $prefix = date('Y-m-d H:i:s') . "\t---\t";

        if (file_put_contents($fileName, $prefix . $msg . PHP_EOL, FILE_APPEND))
        {
            return true;
        }

        return false;

    }

    /**
     * @param $msg
     * @param string $path
     * @return Log
     */
    public static function info($msg, $path = '')
    {
        return new Log($msg, $path);
    }
}

 

執行命令:git

 

composer dump-autoload

 

在控制器中調用方法:github

 

Log::info(json_encode($_SERVER));

 

能夠看到在log目錄下生成了日誌文件:json

相關文章
相關標籤/搜索