File.php 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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. $cli = PHP_SAPI == 'cli' ? '_cli' : '';
  75. if ($this->config['single']) {
  76. $name = is_string($this->config['single']) ? $this->config['single'] : 'single';
  77. $destination = $this->config['path'] . $name . $cli . '.log';
  78. } else {
  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. } elseif ($this->config['max_files']) {
  108. $name = date('Ymd');
  109. } else {
  110. $name = date('d');
  111. }
  112. return $path . DIRECTORY_SEPARATOR . $name . '_' . $type . $cli . '.log';
  113. }
  114. /**
  115. * 日志写入
  116. * @access protected
  117. * @param array $message 日志信息
  118. * @param string $destination 日志文件
  119. * @param bool $apart 是否独立文件写入
  120. * @param bool $append 是否追加请求信息
  121. * @return bool
  122. */
  123. protected function write($message, $destination, $apart = false, $append = false)
  124. {
  125. // 检测日志文件大小,超过配置大小则备份日志文件重新生成
  126. $this->checkLogSize($destination);
  127. // 日志信息封装
  128. $info['timestamp'] = date($this->config['time_format']);
  129. foreach ($message as $type => $msg) {
  130. $msg = is_array($msg) ? implode("\r\n", $msg) : $msg;
  131. if (PHP_SAPI == 'cli') {
  132. $info['msg'] = $msg;
  133. $info['type'] = $type;
  134. } else {
  135. $info[$type] = $msg;
  136. }
  137. }
  138. if (PHP_SAPI == 'cli') {
  139. $message = $this->parseCliLog($info);
  140. } else {
  141. // 添加调试日志
  142. $this->getDebugLog($info, $append, $apart);
  143. $message = $this->parseLog($info);
  144. }
  145. return error_log($message, 3, $destination);
  146. }
  147. /**
  148. * 检查日志文件大小并自动生成备份文件
  149. * @access protected
  150. * @param string $destination 日志文件
  151. * @return void
  152. */
  153. protected function checkLogSize($destination)
  154. {
  155. if (is_file($destination) && floor($this->config['file_size']) <= filesize($destination)) {
  156. try {
  157. rename($destination, dirname($destination) . DIRECTORY_SEPARATOR . time() . '-' . basename($destination));
  158. } catch (\Exception $e) {
  159. }
  160. }
  161. }
  162. /**
  163. * CLI日志解析
  164. * @access protected
  165. * @param array $info 日志信息
  166. * @return string
  167. */
  168. protected function parseCliLog($info)
  169. {
  170. if ($this->config['json']) {
  171. $message = json_encode($info, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\r\n";
  172. } else {
  173. $now = $info['timestamp'];
  174. unset($info['timestamp']);
  175. $message = implode("\r\n", $info);
  176. $message = "[{$now}]" . $message . "\r\n";
  177. }
  178. return $message;
  179. }
  180. /**
  181. * 解析日志
  182. * @access protected
  183. * @param array $info 日志信息
  184. * @return string
  185. */
  186. protected function parseLog($info)
  187. {
  188. $request = Request::instance();
  189. $requestInfo = [
  190. 'ip' => $request->ip(),
  191. 'method' => $request->method(),
  192. 'host' => $request->host(),
  193. 'uri' => $request->url(),
  194. ];
  195. if ($this->config['json']) {
  196. $info = $requestInfo + $info;
  197. return json_encode($info, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\r\n";
  198. }
  199. array_unshift($info, "---------------------------------------------------------------\r\n[{$info['timestamp']}] {$requestInfo['ip']} {$requestInfo['method']} {$requestInfo['host']}{$requestInfo['uri']}");
  200. unset($info['timestamp']);
  201. return implode("\r\n", $info) . "\r\n";
  202. }
  203. protected function getDebugLog(&$info, $append, $apart)
  204. {
  205. if (App::$debug && $append) {
  206. if ($this->config['json']) {
  207. // 获取基本信息
  208. $runtime = round(microtime(true) - THINK_START_TIME, 10);
  209. $reqs = $runtime > 0 ? number_format(1 / $runtime, 2) : '∞';
  210. $memory_use = number_format((memory_get_usage() - THINK_START_MEM) / 1024, 2);
  211. $info = [
  212. 'runtime' => number_format($runtime, 6) . 's',
  213. 'reqs' => $reqs . 'req/s',
  214. 'memory' => $memory_use . 'kb',
  215. 'file' => count(get_included_files()),
  216. ] + $info;
  217. } elseif (!$apart) {
  218. // 增加额外的调试信息
  219. $runtime = round(microtime(true) - THINK_START_TIME, 10);
  220. $reqs = $runtime > 0 ? number_format(1 / $runtime, 2) : '∞';
  221. $memory_use = number_format((memory_get_usage() - THINK_START_MEM) / 1024, 2);
  222. $time_str = '[运行时间:' . number_format($runtime, 6) . 's] [吞吐率:' . $reqs . 'req/s]';
  223. $memory_str = ' [内存消耗:' . $memory_use . 'kb]';
  224. $file_load = ' [文件加载:' . count(get_included_files()) . ']';
  225. array_unshift($info, $time_str . $memory_str . $file_load);
  226. }
  227. }
  228. }
  229. }