File.php 9.0 KB

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