-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.c
94 lines (75 loc) · 1.75 KB
/
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
91
92
93
94
#define _DEFAULT_SOURCE
#include"logger.h"
enum LogLevel
{
INFO,
WARNING,
ERROR,
DEBUG
};
struct Logger
{
enum LogLevel level;
FILE *handler;
};
struct Logger *create_logger(enum LogLevel level, FILE *handler)
{
struct Logger *logger = (struct Logger *)malloc(sizeof(struct Logger));
if (logger == NULL) return NULL;
logger->handler = handler;
logger->level = level;
return logger;
}
time_t get_current_time(void)
{
return time(NULL);
}
void logger_log(const char *str, struct Logger *logger)
{
time_t current_time = get_current_time();
switch (logger->level)
{
case INFO:
{
fprintf(logger->handler, "[%s] [INFO] %s\n", ctime(¤t_time), str);
} break;
case WARNING:
{
fprintf(logger->handler, "[%s] [WARNING] %s\n", ctime(¤t_time), str);
} break;
case ERROR:
{
fprintf(logger->handler, "[%s] [ERROR] %s\n", ctime(¤t_time), str);
} break;
case DEBUG:
{
fprintf(logger->handler, "[%s] [DEBUG] %s\n", ctime(¤t_time), str);
} break;
}
}
void clear_logger(struct Logger *logger)
{
fflush(logger->handler);
int fd = fileno(logger->handler);
if (ftruncate(fd, 0) == -1)
{
perror("ftruncate");
return;
}
}
void free_logger(struct Logger *logger)
{
fclose(logger->handler);
free(logger);
}
int main(void)
{
FILE *file = fopen("log_file.log", "a");
if (file == NULL) return -1;
struct Logger *logger = create_logger(DEBUG, file);
logger_log("Hello, World!", logger);
logger_log("Hello, World!", logger);
clear_logger(logger);
free_logger(logger);
return 0;
}