KafkaProducer.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. /* *****************************************************************
  3. * @Author: wushuiyong
  4. * @Created Time : 六 7/18 22:47:22 2015
  5. *
  6. * @File Name: KafkaProducer.php
  7. * @Description:
  8. * *****************************************************************/
  9. namespace app\components;
  10. use app\components\ZKafka;
  11. class KafkaProducer {
  12. const KAFKA_OFFSET = 'kafka_offset';
  13. const LOG = 'log';
  14. // log topic
  15. const TOPIC_ERROR = 'error';
  16. const TOPIC_WARNING = 'warning';
  17. const TOPIC_NOTICE = 'notice';
  18. // log level
  19. const LEVEL_ERROR = 'error';
  20. const LEVEL_WARNING = 'warning';
  21. const LEVEL_NOTICE = 'notice';
  22. // kafka offset
  23. const KAFKA_ERROR_OFFSET = 'kafka_error_offset';
  24. const KAFKA_WARNING_OFFSET = 'kafka_warning_offset';
  25. const KAFKA_NOTICE_OFFSET = 'kafka_notice_offset';
  26. public static function error($name, $log) {
  27. $trace = debug_backtrace(false);
  28. foreach ($trace as &$line) {
  29. unset($line['args']);
  30. }
  31. return static::write(static::TOPIC_ERROR, static::LEVEL_ERROR, $name, $log, $trace);
  32. }
  33. public static function warning($name, $log) {
  34. $trace = debug_backtrace(false);
  35. foreach ($trace as &$line) {
  36. unset($line['args']);
  37. }
  38. return static::write(static::TOPIC_WARNING, static::LEVEL_WARNING, $name, $log, $trace);
  39. }
  40. public static function notice($name, $log) {
  41. $trace = debug_backtrace(false);
  42. foreach ($trace as &$line) {
  43. unset($line['args']);
  44. }
  45. return static::write(static::TOPIC_NOTICE, static::LEVEL_NOTICE, $name, $log, $trace);
  46. }
  47. public static function write($topic, $level, $name, $log, $trace) {
  48. $trace = static::formatTrace($trace);
  49. $message = json_encode([
  50. 'name' => $name,
  51. 'log' => $log,
  52. 'level' => $level,
  53. 'trace' => json_encode($trace),
  54. 'request' => $_SERVER,
  55. 'time' => date("Y-m-d H:i:s", time()),
  56. ], JSON_UNESCAPED_UNICODE);
  57. d($topic);d($message);
  58. return ZKafka::produce($topic, $message);
  59. }
  60. public static function formatTrace($trace) {
  61. $format = [];
  62. foreach ($trace as $line) {
  63. $format[] = sprintf("%s %s",
  64. empty($line['file']) ? '' : $line['file'] . ':' .$line['line'],
  65. empty($line['class']) ? '' : stripslashes($line['class']) . $line['type'] . $line['function']);
  66. }
  67. return $format;
  68. }
  69. }