nlog.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #include "nlog.h"
  2. #include "list.h"
  3. #include "hdef.h"
  4. #include "hbase.h"
  5. #include "hsocket.h"
  6. #include "hmutex.h"
  7. typedef struct network_logger_s {
  8. hloop_t* loop;
  9. hio_t* listenio;
  10. struct list_head clients;
  11. } network_logger_t;
  12. typedef struct nlog_client {
  13. hio_t* io;
  14. struct list_node node;
  15. } nlog_client;
  16. static network_logger_t s_logger = {0};
  17. static hmutex_t s_mutex;
  18. static void on_close(hio_t* io) {
  19. printd("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io));
  20. nlog_client* client = (nlog_client*)hevent_userdata(io);
  21. if (client) {
  22. hevent_set_userdata(io, NULL);
  23. hmutex_lock(&s_mutex);
  24. list_del(&client->node);
  25. hmutex_unlock(&s_mutex);
  26. HV_FREE(client);
  27. }
  28. }
  29. static void on_read(hio_t* io, void* buf, int readbytes) {
  30. printd("on_read fd=%d readbytes=%d\n", hio_fd(io), readbytes);
  31. printd("< %s\n", (char*)buf);
  32. // nothing to do
  33. }
  34. static void on_accept(hio_t* io) {
  35. /*
  36. printd("on_accept connfd=%d\n", hio_fd(io));
  37. char localaddrstr[SOCKADDR_STRLEN] = {0};
  38. char peeraddrstr[SOCKADDR_STRLEN] = {0};
  39. printd("accept connfd=%d [%s] <= [%s]\n", hio_fd(io),
  40. SOCKADDR_STR(hio_localaddr(io), localaddrstr),
  41. SOCKADDR_STR(hio_peeraddr(io), peeraddrstr));
  42. */
  43. hio_setcb_read(io, on_read);
  44. hio_setcb_close(io, on_close);
  45. hio_read(io);
  46. // free on_close
  47. nlog_client* client;
  48. HV_ALLOC_SIZEOF(client);
  49. client->io = io;
  50. hevent_set_userdata(io, client);
  51. hmutex_lock(&s_mutex);
  52. list_add(&client->node, &s_logger.clients);
  53. hmutex_unlock(&s_mutex);
  54. }
  55. void network_logger(int loglevel, const char* buf, int len) {
  56. struct list_node* node;
  57. nlog_client* client;
  58. hmutex_lock(&s_mutex);
  59. list_for_each (node, &s_logger.clients) {
  60. client = list_entry(node, nlog_client, node);
  61. hio_write(client->io, buf, len);
  62. }
  63. hmutex_unlock(&s_mutex);
  64. }
  65. hio_t* nlog_listen(hloop_t* loop, int port) {
  66. s_logger.loop = loop;
  67. s_logger.listenio = hloop_create_tcp_server(loop, "0.0.0.0", port, on_accept);
  68. list_init(&s_logger.clients);
  69. hmutex_init(&s_mutex);
  70. return s_logger.listenio;
  71. }