Logger.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. <?php
  2. namespace Joypack\Tencent\Map;
  3. /**
  4. * 腾讯位置服务
  5. * 日志管理
  6. */
  7. class Logger
  8. {
  9. protected $rootPath;
  10. protected $development = false;
  11. public function __construct($root_path, $development)
  12. {
  13. $this->development = $development;
  14. if($root_path) {
  15. if(is_dir($root_path)) {
  16. $this->rootPath = $root_path;
  17. } else {
  18. if(@mkdir($root_path, 0775, true)) {
  19. $this->rootPath = $root_path;
  20. }
  21. }
  22. }
  23. }
  24. public function __toString()
  25. {
  26. return __CLASS__;
  27. }
  28. /**
  29. * 写入 debug 日志
  30. * @param string $message
  31. * @param string | array $data
  32. */
  33. public function debug($message, $data=null)
  34. {
  35. $this->save($message, $data, 'DEBUG');
  36. }
  37. /**
  38. * 写入 INFO 日志
  39. * @param string $message
  40. * @param string | array $data
  41. */
  42. public function info($message, $data=null)
  43. {
  44. $this->save($message, $data, 'INFO');
  45. }
  46. /**
  47. * 写入 ERROR 日志
  48. * @param string $message
  49. * @param string | array $data
  50. */
  51. public function error($message, $data=null)
  52. {
  53. $this->save($message, $data, 'ERROR');
  54. }
  55. /**
  56. * 打印变量
  57. * @param mixed $args 打印列表
  58. * 最后一个元素如果是 true 则 exit
  59. */
  60. public function print(...$args)
  61. {
  62. $args = func_get_args();
  63. $length = count($args);
  64. $exit = false;
  65. if(is_bool($last_argument = $args[$length-1])) {
  66. if($last_argument) {
  67. $exit = true;
  68. array_pop($args);
  69. }
  70. }
  71. echo '<pre>';
  72. while ($argument = array_shift($args)) {
  73. print_r($argument);
  74. echo '<br/><br/>';
  75. }
  76. echo '</pre>';
  77. if($exit) {
  78. exit;
  79. }
  80. }
  81. protected function save($message, $data, $level)
  82. {
  83. if(is_null($this->rootPath)) {
  84. return;
  85. }
  86. // 生产环境时只记录错误信息
  87. if(!$this->development) {
  88. if($level != 'ERROR') {
  89. return;
  90. }
  91. }
  92. $date = date('Y-m-d');
  93. $now = date('Y-m-d H:i:s');
  94. $filename = "{$this->rootPath}/{$date}.log";
  95. if(is_array($data)) {
  96. $data = json_encode($data, JSON_UNESCAPED_UNICODE);
  97. }
  98. @file_put_contents($filename, "[{$level}] {$now} {$message} {$data}\r\n", FILE_APPEND);
  99. }
  100. }