nlog.c 2.2 KB

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