-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlog.c
101 lines (90 loc) · 2.21 KB
/
log.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
95
96
97
98
99
100
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
#include <stdarg.h>
#include "log.h"
#define TIME_LEN 64
static char curr_time[TIME_LEN];
static int log2screen = 1;
static int log2file;
static char log_file_name[128];
static FILE *log_fp = NULL;
static int log_level = DEBUG;
struct {
char text[8];
char ctext[16];
}log_text[]={
{"DEBUG", "\033[1;32mDEBUG"},
{"INFO", "\033[1;36mINFO"},
{"WARN", "\033[1;33mWARNING"},
{"ERROR", "\033[1;35mERROR"},
{"FATAL", "\033[1;31mFATAL"}
};
static char *print_lv_text(int lv, int color){
if(color) return log_text[lv].ctext;
else return log_text[lv].text;
}
static char *print_time()
{
time_t now;
struct timeval tv;
struct tm *nowtm;
gettimeofday(&tv, NULL);
now = tv.tv_sec;
nowtm = localtime(&now);
char timebuf[TIME_LEN];
strftime(timebuf, TIME_LEN, "%Y-%m-%d %H:%M:%S", nowtm);
snprintf(curr_time, TIME_LEN + 32, "%s %06ld",timebuf, (long)tv.tv_usec);
return curr_time;
}
int log_set_level(int level)
{
if(level < DEBUG || level > FATAL) return -1;
log_level = level;
return 0;
}
int log_set_opt(int opt);
static int log_open_file()
{
log_fp = fopen(log_file_name, "w");
LOG(INFO, "Log file save to %s\n", log_file_name);
return 0;
}
int log_set_file(char *file)
{
strncpy(log_file_name, file, 128);
log2file = 1;
log_open_file();
return 0;
}
int log_close_file()
{
if(log_fp){
fclose(log_fp);
log_fp = NULL;
}
return 0;
}
void log_print(int level, char *file, int line, char *fmt, ...)
{
char buf[1024];
va_list vl;
va_start(vl, fmt);
vsnprintf(buf, sizeof(buf),fmt, vl);
va_end(vl);
if(log2screen){
if(level < log_level) return;
#ifdef COLOR_LOG
fprintf(stderr, "%16s| %s ( %s:%d ) %s", print_lv_text(level, 1), print_time(), file, line, buf);
fprintf(stderr, "\033[0m");
#else
fprintf(stderr, "%8s| %s ( %s:%d ) %s", print_lv_text(level, 0), print_time(), file, line, buf);
#endif
}
if(log2file && log_fp){
if(level < log_level) return;
fprintf(log_fp, "%s %s ( %s:%d ) %s", print_lv_text(level, 0), print_time(), file, line, buf);
}
}