LogService.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Bear
  5. * Date: 2018/10/23
  6. * Time: 上午10:28
  7. */
  8. namespace app\common\service;
  9. use think\Log;
  10. class LogService
  11. {
  12. /**
  13. * 细节级别
  14. * @param $msg
  15. */
  16. public static function debug($msg)
  17. {
  18. self::log($msg, 'debug');
  19. }
  20. /**
  21. * 了解级别
  22. * @param $msg
  23. */
  24. public static function info($msg)
  25. {
  26. self::log($msg, 'info');
  27. }
  28. /**
  29. * 通知级别
  30. * @param $msg
  31. */
  32. public static function notice($msg)
  33. {
  34. self::log($msg, 'notice');
  35. }
  36. /**
  37. * 错误级别
  38. * @param $msg
  39. */
  40. public static function error($msg)
  41. {
  42. self::log($msg, 'error');
  43. }
  44. /**
  45. * 告警级别
  46. * @param string $msg
  47. */
  48. public static function alert($msg)
  49. {
  50. self::log($msg, 'alert');
  51. }
  52. /**
  53. * 紧急级别
  54. * @param string $msg
  55. */
  56. public static function critical($msg)
  57. {
  58. self::log($msg, 'alert');
  59. }
  60. /**
  61. * @param string $msg
  62. * @param string $level
  63. */
  64. public static function log($msg, $level)
  65. {
  66. $msg = "time:[ " . date('Y-m-d H:i:s') . " ]\t" . $msg;
  67. Log::record($msg, $level);
  68. }
  69. /**
  70. * @param \Exception $e
  71. * @return array
  72. */
  73. public static function exception(\Exception $e)
  74. {
  75. $msg = json_encode([
  76. $e->getMessage(),
  77. $e->getFile(),
  78. $e->getLine(),
  79. ]);
  80. return self::toError($e->getCode(), $msg, 'critical');
  81. }
  82. /**
  83. * 格式化错误返回值
  84. * @param $error_code
  85. * @param $error_msg
  86. * @param string $level
  87. * @return array
  88. */
  89. public static function toError($error_code, $error_msg, $level = 'error')
  90. {
  91. if (is_array($error_msg)) {
  92. $error_msg = json_encode($error_msg);
  93. }
  94. $return = ['error' => $error_code, 'msg' => $error_msg];
  95. //将进程id写入日志,方便定位
  96. self::log("errcode:[ $error_code ]\terrmsg:[ $error_msg ]", $level);
  97. return $return;
  98. }
  99. /**
  100. * 格式化成功返回值
  101. * @param $error_code
  102. * @param $error_msg
  103. * @param string $level
  104. * @return array
  105. */
  106. public static function toSuccess($error_code, $error_msg, $level = 'debug')
  107. {
  108. if (is_array($error_msg)) {
  109. $error_msg = json_encode($error_msg);
  110. }
  111. $return = ['error' => $error_code, 'msg' => $error_msg];
  112. //将进程id写入日志,方便定位
  113. self::log("errcode:[ $error_code ]\terrmsg:[ $error_msg ]", $level);
  114. return $return;
  115. }
  116. }