在 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