File.php 9.1 KB

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