service_logger.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #include "skynet.h"
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <stdint.h>
  5. #include <string.h>
  6. #include <time.h>
  7. struct logger {
  8. FILE * handle;
  9. char * filename;
  10. uint32_t starttime;
  11. int close;
  12. };
  13. struct logger *
  14. logger_create(void) {
  15. struct logger * inst = skynet_malloc(sizeof(*inst));
  16. inst->handle = NULL;
  17. inst->close = 0;
  18. inst->filename = NULL;
  19. return inst;
  20. }
  21. void
  22. logger_release(struct logger * inst) {
  23. if (inst->close) {
  24. fclose(inst->handle);
  25. }
  26. skynet_free(inst->filename);
  27. skynet_free(inst);
  28. }
  29. #define SIZETIMEFMT 250
  30. static int
  31. timestring(struct logger *inst, char tmp[SIZETIMEFMT]) {
  32. uint64_t now = skynet_now();
  33. time_t ti = now/100 + inst->starttime;
  34. struct tm info;
  35. (void)localtime_r(&ti,&info);
  36. strftime(tmp, SIZETIMEFMT, "%d/%m/%y %H:%M:%S", &info);
  37. return now % 100;
  38. }
  39. static int
  40. logger_cb(struct skynet_context * context, void *ud, int type, int session, uint32_t source, const void * msg, size_t sz) {
  41. struct logger * inst = ud;
  42. switch (type) {
  43. case PTYPE_SYSTEM:
  44. if (inst->filename) {
  45. inst->handle = freopen(inst->filename, "a", inst->handle);
  46. }
  47. break;
  48. case PTYPE_TEXT:
  49. if (inst->filename) {
  50. char tmp[SIZETIMEFMT];
  51. int csec = timestring(ud, tmp);
  52. fprintf(inst->handle, "%s.%02d ", tmp, csec);
  53. }
  54. fprintf(inst->handle, "[:%08x] ", source);
  55. fwrite(msg, sz , 1, inst->handle);
  56. fprintf(inst->handle, "\n");
  57. fflush(inst->handle);
  58. break;
  59. }
  60. return 0;
  61. }
  62. int
  63. logger_init(struct logger * inst, struct skynet_context *ctx, const char * parm) {
  64. const char * r = skynet_command(ctx, "STARTTIME", NULL);
  65. inst->starttime = strtoul(r, NULL, 10);
  66. if (parm) {
  67. inst->handle = fopen(parm,"a");
  68. if (inst->handle == NULL) {
  69. return 1;
  70. }
  71. inst->filename = skynet_malloc(strlen(parm)+1);
  72. strcpy(inst->filename, parm);
  73. inst->close = 1;
  74. } else {
  75. inst->handle = stdout;
  76. }
  77. if (inst->handle) {
  78. skynet_callback(ctx, inst, logger_cb);
  79. return 0;
  80. }
  81. return 1;
  82. }