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
|
#include "log.h"
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "err.h"
FILE *log_file = NULL;
void
log_init(void)
{
log_file = fopen(LOG_FILEPATH, "a");
if (!log_file) {
die("Faild to open log file");
}
}
void
log_write(log_level level, const char *fmt, ...)
{
char *level_str;
if (level == LOG_INFO)
level_str = "INFO";
if (level == LOG_WARN)
level_str = "WARN";
if (level == LOG_ERR)
level_str = "ERR";
time_t rawtime;
struct tm *timeinfo;
char time_str[32];
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", timeinfo);
fprintf(log_file, "[%s] [%s] ", time_str, level_str);
va_list ap;
va_start(ap, fmt);
vfprintf(log_file, fmt, ap);
va_end(ap);
fprintf(log_file, "\n");
fflush(log_file);
}
void
log_end(FILE *log_file)
{
if (log_file) {
fclose(log_file);
log_file = NULL;
}
}
|