You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

271 lines
8.4 KiB

  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace think\log\driver;
  12. use think\App;
  13. use think\Request;
  14. /**
  15. * 本地化调试输出到文件
  16. */
  17. class File
  18. {
  19. protected $config = [
  20. 'time_format' => ' c ',
  21. 'single' => false,
  22. 'file_size' => 2097152,
  23. 'path' => LOG_PATH,
  24. 'apart_level' => [],
  25. 'max_files' => 0,
  26. 'json' => false,
  27. ];
  28. // 实例化并传入参数
  29. public function __construct($config = [])
  30. {
  31. if (is_array($config)) {
  32. $this->config = array_merge($this->config, $config);
  33. }
  34. }
  35. /**
  36. * 日志写入接口
  37. * @access public
  38. * @param array $log 日志信息
  39. * @param bool $append 是否追加请求信息
  40. * @return bool
  41. */
  42. public function save(array $log = [], $append = false)
  43. {
  44. $destination = $this->getMasterLogFile();
  45. $path = dirname($destination);
  46. !is_dir($path) && mkdir($path, 0755, true);
  47. $info = [];
  48. foreach ($log as $type => $val) {
  49. foreach ($val as $msg) {
  50. if (!is_string($msg)) {
  51. $msg = var_export($msg, true);
  52. }
  53. $info[$type][] = $this->config['json'] ? $msg : '[ ' . $type . ' ] ' . $msg;
  54. }
  55. if (!$this->config['json'] && (true === $this->config['apart_level'] || in_array($type, $this->config['apart_level']))) {
  56. // 独立记录的日志级别
  57. $filename = $this->getApartLevelFile($path, $type);
  58. $this->write($info[$type], $filename, true, $append);
  59. unset($info[$type]);
  60. }
  61. }
  62. if ($info) {
  63. return $this->write($info, $destination, false, $append);
  64. }
  65. return true;
  66. }
  67. /**
  68. * 获取主日志文件名
  69. * @access public
  70. * @return string
  71. */
  72. protected function getMasterLogFile()
  73. {
  74. if ($this->config['single']) {
  75. $name = is_string($this->config['single']) ? $this->config['single'] : 'single';
  76. $destination = $this->config['path'] . $name . '.log';
  77. } else {
  78. $cli = PHP_SAPI == 'cli' ? '_cli' : '';
  79. if ($this->config['max_files']) {
  80. $filename = date('Ymd') . $cli . '.log';
  81. $files = glob($this->config['path'] . '*.log');
  82. try {
  83. if (count($files) > $this->config['max_files']) {
  84. unlink($files[0]);
  85. }
  86. } catch (\Exception $e) {
  87. }
  88. } else {
  89. $filename = date('Ym') . DIRECTORY_SEPARATOR . date('d') . $cli . '.log';
  90. }
  91. $destination = $this->config['path'] . $filename;
  92. }
  93. return $destination;
  94. }
  95. /**
  96. * 获取独立日志文件名
  97. * @access public
  98. * @param string $path 日志目录
  99. * @param string $type 日志类型
  100. * @return string
  101. */
  102. protected function getApartLevelFile($path, $type)
  103. {
  104. $cli = PHP_SAPI == 'cli' ? '_cli' : '';
  105. if ($this->config['single']) {
  106. $name = is_string($this->config['single']) ? $this->config['single'] : 'single';
  107. $name .= '_' . $type;
  108. } elseif ($this->config['max_files']) {
  109. $name = date('Ymd') . '_' . $type . $cli;
  110. } else {
  111. $name = date('d') . '_' . $type . $cli;
  112. }
  113. return $path . DIRECTORY_SEPARATOR . $name . '.log';
  114. }
  115. /**
  116. * 日志写入
  117. * @access protected
  118. * @param array $message 日志信息
  119. * @param string $destination 日志文件
  120. * @param bool $apart 是否独立文件写入
  121. * @param bool $append 是否追加请求信息
  122. * @return bool
  123. */
  124. protected function write($message, $destination, $apart = false, $append = false)
  125. {
  126. // 检测日志文件大小,超过配置大小则备份日志文件重新生成
  127. $this->checkLogSize($destination);
  128. // 日志信息封装
  129. $info['timestamp'] = date($this->config['time_format']);
  130. foreach ($message as $type => $msg) {
  131. $info[$type] = is_array($msg) ? implode("\r\n", $msg) : $msg;
  132. }
  133. if (PHP_SAPI == 'cli') {
  134. $message = $this->parseCliLog($info);
  135. } else {
  136. // 添加调试日志
  137. $this->getDebugLog($info, $append, $apart);
  138. $message = $this->parseLog($info);
  139. }
  140. return error_log($message, 3, $destination);
  141. }
  142. /**
  143. * 检查日志文件大小并自动生成备份文件
  144. * @access protected
  145. * @param string $destination 日志文件
  146. * @return void
  147. */
  148. protected function checkLogSize($destination)
  149. {
  150. if (is_file($destination) && floor($this->config['file_size']) <= filesize($destination)) {
  151. try {
  152. rename($destination, dirname($destination) . DIRECTORY_SEPARATOR . time() . '-' . basename($destination));
  153. } catch (\Exception $e) {
  154. }
  155. }
  156. }
  157. /**
  158. * CLI日志解析
  159. * @access protected
  160. * @param array $info 日志信息
  161. * @return string
  162. */
  163. protected function parseCliLog($info)
  164. {
  165. if ($this->config['json']) {
  166. $message = json_encode($info, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\r\n";
  167. } else {
  168. $now = $info['timestamp'];
  169. unset($info['timestamp']);
  170. $message = implode("\r\n", $info);
  171. $message = "[{$now}]" . $message . "\r\n";
  172. }
  173. return $message;
  174. }
  175. /**
  176. * 解析日志
  177. * @access protected
  178. * @param array $info 日志信息
  179. * @return string
  180. */
  181. protected function parseLog($info)
  182. {
  183. $request = Request::instance();
  184. $requestInfo = [
  185. 'ip' => $request->ip(),
  186. 'method' => $request->method(),
  187. 'host' => $request->host(),
  188. 'uri' => $request->url(),
  189. ];
  190. if ($this->config['json']) {
  191. $info = $requestInfo + $info;
  192. return json_encode($info, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\r\n";
  193. }
  194. array_unshift($info, "---------------------------------------------------------------\r\n[{$info['timestamp']}] {$requestInfo['ip']} {$requestInfo['method']} {$requestInfo['host']}{$requestInfo['uri']}");
  195. unset($info['timestamp']);
  196. return implode("\r\n", $info) . "\r\n";
  197. }
  198. protected function getDebugLog(&$info, $append, $apart)
  199. {
  200. if (App::$debug && $append) {
  201. if ($this->config['json']) {
  202. // 获取基本信息
  203. $runtime = round(microtime(true) - THINK_START_TIME, 10);
  204. $reqs = $runtime > 0 ? number_format(1 / $runtime, 2) : '∞';
  205. $memory_use = number_format((memory_get_usage() - THINK_START_MEM) / 1024, 2);
  206. $info = [
  207. 'runtime' => number_format($runtime, 6) . 's',
  208. 'reqs' => $reqs . 'req/s',
  209. 'memory' => $memory_use . 'kb',
  210. 'file' => count(get_included_files()),
  211. ] + $info;
  212. } elseif (!$apart) {
  213. // 增加额外的调试信息
  214. $runtime = round(microtime(true) - THINK_START_TIME, 10);
  215. $reqs = $runtime > 0 ? number_format(1 / $runtime, 2) : '∞';
  216. $memory_use = number_format((memory_get_usage() - THINK_START_MEM) / 1024, 2);
  217. $time_str = '[运行时间:' . number_format($runtime, 6) . 's] [吞吐率:' . $reqs . 'req/s]';
  218. $memory_str = ' [内存消耗:' . $memory_use . 'kb]';
  219. $file_load = ' [文件加载:' . count(get_included_files()) . ']';
  220. array_unshift($info, $time_str . $memory_str . $file_load);
  221. }
  222. }
  223. }
  224. }