skynet_error.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #include "skynet.h"
  2. #include "skynet_handle.h"
  3. #include "skynet_mq.h"
  4. #include "skynet_server.h"
  5. #include <stdarg.h>
  6. #include <stdio.h>
  7. #include <string.h>
  8. #include <stdlib.h>
  9. #define LOG_MESSAGE_SIZE 256
  10. void
  11. skynet_error(struct skynet_context * context, const char *msg, ...) {
  12. static uint32_t logger = 0;
  13. if (logger == 0) {
  14. logger = skynet_handle_findname("logger");
  15. }
  16. if (logger == 0) {
  17. return;
  18. }
  19. char tmp[LOG_MESSAGE_SIZE];
  20. char *data = NULL;
  21. va_list ap;
  22. va_start(ap,msg);
  23. int len = vsnprintf(tmp, LOG_MESSAGE_SIZE, msg, ap);
  24. va_end(ap);
  25. if (len >=0 && len < LOG_MESSAGE_SIZE) {
  26. data = skynet_strdup(tmp);
  27. } else {
  28. int max_size = LOG_MESSAGE_SIZE;
  29. for (;;) {
  30. max_size *= 2;
  31. data = skynet_malloc(max_size);
  32. va_start(ap,msg);
  33. len = vsnprintf(data, max_size, msg, ap);
  34. va_end(ap);
  35. if (len < max_size) {
  36. break;
  37. }
  38. skynet_free(data);
  39. }
  40. }
  41. if (len < 0) {
  42. skynet_free(data);
  43. perror("vsnprintf error :");
  44. return;
  45. }
  46. struct skynet_message smsg;
  47. if (context == NULL) {
  48. smsg.source = 0;
  49. } else {
  50. smsg.source = skynet_context_handle(context);
  51. }
  52. smsg.session = 0;
  53. smsg.data = data;
  54. smsg.sz = len | ((size_t)PTYPE_TEXT << MESSAGE_TYPE_SHIFT);
  55. skynet_context_push(logger, &smsg);
  56. }