构建本身的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

相关文章
相关标签/搜索