nlog.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. hmutex_lock(&s_mutex);
  21. struct list_node* next = s_logger.clients.next;
  22. nlog_client* client;
  23. while (next != &s_logger.clients) {
  24. client = list_entry(next, nlog_client, node);
  25. next = next->next;
  26. if (client->io == io) {
  27. list_del(next->prev);
  28. HV_FREE(client);
  29. break;
  30. }
  31. }
  32. hmutex_unlock(&s_mutex);
  33. }
  34. static void on_read(hio_t* io, void* buf, int readbytes) {
  35. printd("on_read fd=%d readbytes=%d\n", hio_fd(io), readbytes);
  36. printd("< %s\n", (char*)buf);
  37. // nothing to do
  38. }
  39. static void on_accept(hio_t* io) {
  40. /*
  41. printd("on_accept connfd=%d\n", hio_fd(io));
  42. char localaddrstr[SOCKADDR_STRLEN] = {0};
  43. char peeraddrstr[SOCKADDR_STRLEN] = {0};
  44. printd("accept connfd=%d [%s] <= [%s]\n", hio_fd(io),
  45. SOCKADDR_STR(hio_localaddr(io), localaddrstr),
  46. SOCKADDR_STR(hio_peeraddr(io), peeraddrstr));
  47. */
  48. hio_setcb_read(io, on_read);
  49. hio_setcb_close(io, on_close);
  50. hio_read(io);
  51. // free on_close
  52. nlog_client* client;
  53. HV_ALLOC_SIZEOF(client);
  54. client->io = io;
  55. hmutex_lock(&s_mutex);
  56. list_add(&client->node, &s_logger.clients);
  57. hmutex_unlock(&s_mutex);
  58. }
  59. void network_logger(int loglevel, const char* buf, int len) {
  60. struct list_node* node;
  61. nlog_client* client;
  62. hmutex_lock(&s_mutex);
  63. list_for_each (node, &s_logger.clients) {
  64. client = list_entry(node, nlog_client, node);
  65. hio_write(client->io, buf, len);
  66. }
  67. hmutex_unlock(&s_mutex);
  68. }
  69. hio_t* nlog_listen(hloop_t* loop, int port) {
  70. list_init(&s_logger.clients);
  71. s_logger.loop = loop;
  72. s_logger.listenio = hloop_create_tcp_server(loop, "0.0.0.0", port, on_accept);
  73. hmutex_init(&s_mutex);
  74. return s_logger.listenio;
  75. }