skynet_log.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include "skynet_log.h"
  2. #include "skynet_timer.h"
  3. #include "skynet.h"
  4. #include "skynet_socket.h"
  5. #include <string.h>
  6. #include <time.h>
  7. FILE *
  8. skynet_log_open(struct skynet_context * ctx, uint32_t handle) {
  9. const char * logpath = skynet_getenv("logpath");
  10. if (logpath == NULL)
  11. return NULL;
  12. size_t sz = strlen(logpath);
  13. char tmp[sz + 16];
  14. sprintf(tmp, "%s/%08x.log", logpath, handle);
  15. FILE *f = fopen(tmp, "ab");
  16. if (f) {
  17. uint32_t starttime = skynet_starttime();
  18. uint64_t currenttime = skynet_now();
  19. time_t ti = starttime + currenttime/100;
  20. skynet_error(ctx, "Open log file %s", tmp);
  21. fprintf(f, "open time: %u %s", (uint32_t)currenttime, ctime(&ti));
  22. fflush(f);
  23. } else {
  24. skynet_error(ctx, "Open log file %s fail", tmp);
  25. }
  26. return f;
  27. }
  28. void
  29. skynet_log_close(struct skynet_context * ctx, FILE *f, uint32_t handle) {
  30. skynet_error(ctx, "Close log file :%08x", handle);
  31. fprintf(f, "close time: %u\n", (uint32_t)skynet_now());
  32. fclose(f);
  33. }
  34. static void
  35. log_blob(FILE *f, void * buffer, size_t sz) {
  36. size_t i;
  37. uint8_t * buf = buffer;
  38. for (i=0;i!=sz;i++) {
  39. fprintf(f, "%02x", buf[i]);
  40. }
  41. }
  42. static void
  43. log_socket(FILE * f, struct skynet_socket_message * message, size_t sz) {
  44. fprintf(f, "[socket] %d %d %d ", message->type, message->id, message->ud);
  45. if (message->buffer == NULL) {
  46. const char *buffer = (const char *)(message + 1);
  47. sz -= sizeof(*message);
  48. const char * eol = memchr(buffer, '\0', sz);
  49. if (eol) {
  50. sz = eol - buffer;
  51. }
  52. fprintf(f, "[%*s]", (int)sz, (const char *)buffer);
  53. } else {
  54. sz = message->ud;
  55. log_blob(f, message->buffer, sz);
  56. }
  57. fprintf(f, "\n");
  58. fflush(f);
  59. }
  60. void
  61. skynet_log_output(FILE *f, uint32_t source, int type, int session, void * buffer, size_t sz) {
  62. if (type == PTYPE_SOCKET) {
  63. log_socket(f, buffer, sz);
  64. } else {
  65. uint32_t ti = (uint32_t)skynet_now();
  66. fprintf(f, ":%08x %d %d %u ", source, type, session, ti);
  67. log_blob(f, buffer, sz);
  68. fprintf(f,"\n");
  69. fflush(f);
  70. }
  71. }