-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathlog.c
98 lines (97 loc) · 2.78 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
#include "log.h"
#include "assert.h"
LOGGER *initLog()
{
LOGGER *lgr = malloc(sizeof(LOGGER));
lgr->labelCnt = 0;
return lgr;
}
void LogParams(LOGGER * lgr, char *label, char *name, ...)
{
assert(strlen(label) > 0);
assert(strlen(name) > 0);
assert(strlen(name) < LOGCOL);
assert(strlen(name) < LOGCOL);
va_list argp;
va_start(argp, name);
int i,found=0,curlabel=0;
void *c;
char param[160];
vsprintf(param,name,argp);
assert(strlen(param) < LOGCOL);
//Find where the label is in our label array.
for(i=0;i<lgr->labelCnt;i++)
{
if(strcmp(lgr->label[i], label) == 0)
{
found=1;
curlabel=i;
break;
}
}
//New label, add it to the label list
if(!found)
{
curlabel=lgr->labelCnt;
lgr->labelCnt++;
if(lgr->labelCnt == 1)
{
lgr->label = malloc(sizeof(char*));
lgr->line = malloc(sizeof(char*));
lgr->lineMem = malloc(sizeof(int));
}
else
{
lgr->label = realloc(lgr->label, lgr->labelCnt*sizeof(char*));
lgr->line = realloc(lgr->line, lgr->labelCnt*sizeof(char*));
lgr->lineMem = realloc(lgr->lineMem, lgr->labelCnt*sizeof(int));
}
lgr->label[curlabel] = malloc(LOGCOL+1);
lgr->line[curlabel] = malloc(LOGCOL+1);
lgr->lineMem[curlabel] = LOGCOL;
strcpy(lgr->label[curlabel], label);
lgr->line[curlabel][0] = '\0';
}
//Check to see if line is blank, and if so, append the label to it.
if(strlen(lgr->line[curlabel]) == 0)
{
strcat(lgr->line[curlabel], "\n# ");
strcat(lgr->line[curlabel], lgr->label[curlabel]);
strcat(lgr->line[curlabel], ": ");
}
//Check to make sure the line will be under the column limit
if((strlen(lgr->line[curlabel]) + strlen(param)) < lgr->lineMem[curlabel]-1)
{
strcat(lgr->line[curlabel], " ");
strcat(lgr->line[curlabel], param);
}
//If the line is over the limit, write the contents out and start a new line
//with the requested label.
else
{
lgr->line[curlabel] = realloc(lgr->line[curlabel], lgr->lineMem[curlabel]+LOGCOL);
lgr->lineMem[curlabel] += LOGCOL;
strcat(lgr->line[curlabel], "\n# ");
strcat(lgr->line[curlabel], lgr->label[curlabel]);
strcat(lgr->line[curlabel], ": ");
strcat(lgr->line[curlabel], param);
}
va_end(argp);
}
void LogFlush(LOGGER * lgr, FILE *fp)
{
int i;
void *c;
for(i=0;i<lgr->labelCnt;i++)
{
fprintf(fp, lgr->line[i]);
c = lgr->line[i];
free(c);
c = lgr->label[i];
free(c);
}
free(lgr->label);
free(lgr->line);
free(lgr->lineMem);
free(lgr);
}