1
0

nlog.c 2.2 KB

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