-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcustom_logger.c
90 lines (78 loc) · 1.96 KB
/
custom_logger.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/** custom_logger example
* @brief Demonstrates how to create a custom logger that writes log messages to a file.
*/
#include <th.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
static sig_atomic_t stop = 0;
static void
sigint_handler(int signum)
{
stop = signum;
}
static th_err
handler(void* userp, const th_request* req, th_response* resp)
{
(void)userp;
(void)req;
th_set_body(resp, "Hello, Loggers!");
th_add_header(resp, "Content-Type", "text/plain");
return TH_ERR_OK;
}
typedef struct my_logger {
th_log log;
FILE* file;
} my_logger;
static void
my_log(void* self, int level, const char* msg)
{
(void)level;
my_logger* logger = self;
fprintf(logger->file, "%s\n", msg);
}
static bool
my_logger_init(my_logger* log, const char* path)
{
log->log.print = my_log;
log->file = fopen(path, "w");
return log->file != NULL;
}
static void
my_logger_deinit(my_logger* log)
{
fclose(log->file);
}
int main(void)
{
signal(SIGINT, sigint_handler);
// Initialize our custom logger
my_logger logger = {0};
if (!my_logger_init(&logger, "custom_logger.log")) {
fprintf(stderr, "Failed to open log file\n");
return EXIT_FAILURE;
}
th_log_set(&logger.log);
// Startup the server as usual
th_server* server = NULL;
th_err err = TH_ERR_OK;
if ((err = th_server_create(&server, NULL)) != TH_ERR_OK)
goto cleanup_logger;
if ((err = th_bind(server, "0.0.0.0", "8080", NULL)) != TH_ERR_OK)
goto cleanup_server;
if ((err = th_route(server, TH_METHOD_GET, "/", handler, NULL)) != TH_ERR_OK)
goto cleanup_server;
while (!stop) {
th_poll(server, 1000);
}
fprintf(stderr, "Shutting down...\n");
cleanup_server:
th_server_destroy(server);
cleanup_logger:
my_logger_deinit(&logger);
if (err != TH_ERR_OK) {
fprintf(stderr, "Error: %s\n", th_strerror(err));
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}