Geen omschrijving

Log.php 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace App\Support;
  3. use App\Models\Sys\SysLogRecord;
  4. use Monolog\Logger;
  5. use Monolog\Handler\StreamHandler;
  6. use Monolog\Processor\WebProcessor;
  7. class Log
  8. {
  9. private static function _save($name, $content, $extra, $level = Logger::INFO)
  10. {
  11. $logger = new Logger($name);
  12. # 日志文件位置及文件名
  13. $logFilePath = storage_path('kwaiAD/' . date('m-d') . '/' .$name .'.log');
  14. try {
  15. $logger->pushHandler(new StreamHandler($logFilePath), $level);
  16. $logger->pushProcessor(new WebProcessor());
  17. switch($level) {
  18. case Logger::INFO:
  19. $logger->info($content, $extra);
  20. break;
  21. case Logger::ERROR:
  22. $logger->error($content, $extra);
  23. break;
  24. case Logger::DEBUG:
  25. $logger->debug($content, $extra);
  26. break;
  27. default:
  28. $logger->warning('日志类型传递有误,暂时存在三种类型:', ['info', 'error', 'debug']);
  29. }
  30. } catch (\Exception $e) {
  31. $exceptionLogPath = storage_path('logs/exception.log');
  32. file_put_contents($exceptionLogPath, date('Y-m-d H:i:s') . " " . $e->getMessage() . "[". json_encode($extra, JSON_UNESCAPED_UNICODE) ."【".$name."】]". "\r\n", FILE_APPEND);
  33. }
  34. }
  35. /**
  36. * 信息日志
  37. * @param $title
  38. * @param $content
  39. * @param string $file
  40. */
  41. public static function info($content, $extra = [], $prefix = 'info')
  42. {
  43. self::_save($prefix, $content, $extra, Logger::INFO);
  44. }
  45. /**
  46. * 错误日志
  47. * @param $title
  48. * @param $content
  49. * @param string $file
  50. */
  51. public static function error($content, $extra = [], $prefix = 'error')
  52. {
  53. self::_save($prefix, $content, $extra, Logger::ERROR);
  54. if ($prefix != 'exception') {
  55. SysLogRecord::query()->insert([
  56. 'level' => 'ERROR',
  57. 'content' => $content,
  58. 'file' => $prefix
  59. ]);
  60. }
  61. }
  62. /**
  63. * 调试日志
  64. * @param $content
  65. * @param array $extra
  66. * @param string $prefix
  67. */
  68. public static function debug($content, $extra = [], $prefix = 'debug')
  69. {
  70. self::_save($prefix, $content, $extra, Logger::DEBUG);
  71. }
  72. }