log日志方法
<?php /** * 记录日志 * * @package library */ defined('DYMall') or exit('Access Invalid!'); define('BASE_DATA_PATH', '/data'); class Log { const SQL = 'SQL'; const ERR = 'ERR'; const INFO = 'INFO'; const RUN = 'RUN'; private static $log = array(); private static $logFile = "%s%s.log"; //sql日志文件 private static $sqlFile = 'sql_'; /** * Notes:记录 * User: Abel Yang * Date: 2020/5/30/030 * Time: 15:40 * @param $message * @param string $level */ public static function record($message, $level = self::INFO) { $level = strtoupper($level); switch ($level) { case self::INFO: case self::ERR: case self::RUN: self::info($message, $level); break; } } /** * Notes:sql日志 * User: Abel Yang * Date: 2020/5/30/030 * Time: 16:46 * @param $message */ public static function sql($message){ if (C('sql_debug')) { $content = "[" . self::getNow() . "] {$message}\r\n"; self::write($content, self::$sqlFile); } } public static function read() { return self::$log; } /** * Notes:普通日志 * User: Abel Yang * Date: 2020/5/30/030 * Time: 15:39 * @param $message * @param $level */ public static function info($message, $level = self::INFO) { self::write("[" . self::getNow() . "] " . self::getUrl() . "\r\n[{$level}]: {$message}\r\n"); } /** * Notes:错误日志 * User: Abel Yang * Date: 2020/5/30/030 * Time: 15:39 * @param string $message */ public static function error($message = "") { $stack = $message; $debugInfo = debug_backtrace(); foreach ($debugInfo as $key => $val) { if (array_key_exists("file", $val)) $stack .= ",file:" . $val["file"]; if (array_key_exists("line", $val)) $stack .= ",line:" . $val["line"]; if (array_key_exists("function", $val)) $stack .= ",function:" . $val["function"]; } self::info($stack, self::ERR); } private static function write($content, $filePrefix = "") { if (empty($content)) return; $logDir = BASE_DATA_PATH . '/log/'; is_dir($logDir) ?: mkdir($logDir, 0777, true); $fileName = sprintf(self::$logFile, $filePrefix, date('Ymd')); $logFile = $logDir . $fileName; file_put_contents($logFile, "{$content}", FILE_APPEND); } private static function getNow() { list($usec, $sec) = explode(" ", microtime()); return date('Y-m-d H:i:s', $sec) . " " . $usec; } private static function getUrl() { $url = $_SERVER['REQUEST_URI'] ? $_SERVER['REQUEST_URI'] : $_SERVER['PHP_SELF']; $url .= " ( app={$_GET['app']}&mod={$_GET['mod']} ) "; return $url; } }
调用
$error = '用户796邀请797注册'.PHP_EOL;
Log::record($error);
效果
[2020-06-04 15:26:30 0.49780000] /cmobile/index.php?app=members&mod=memberid&key=79ad123033c09a3416449cf03ed23f0b&type=3&memberid=YT78309 ( app=members&mod=memberid )
[INFO]: 用户796邀请797注册