Statistics
| Branch: | Revision:

napa-baselibs / dclog / log.c @ 5f3adef4

History | View | Annotate | Download (1.85 KB)

1
/*
2
 * This file implements logging functionality for the GRAPES framework
3
 */
4

    
5
#define _GNU_SOURCE
6

    
7
#include        <stdio.h>
8
#include        <stdlib.h>
9
#include        <stdarg.h>
10
#include        <grapes_log.h>
11
#include        "dclog.h"
12

    
13
DCLog *dclog = NULL;
14
static char initialized = 0;
15
FILE *logstream = NULL;
16
char *logbuffer = NULL;
17
size_t logbuffer_size = 0;
18

    
19
void grapesInitLog(int log_level, const char *filename, const char *mode) {
20
        if (initialized) return;
21

    
22
        /* Initialize the logger facility */
23
        if ((dclog = NewDCLog()) == NULL) {
24
                fprintf( stderr, "FATAL ERROR: failed to initialize logger!\n" );
25
                exit(-1);
26
        }
27
        if (!filename) filename = "stderr";
28
        if (!mode || strcmp(mode, "a") != 0 || strcmp(mode, "w") != 0) mode = "a";
29

    
30
        if (DCLogOpen( dclog, filename, mode) != 1) {
31
                fprintf( stderr, "FATAL ERROR: failed to initialize logger, logfile: %s, mode: %s!\n", filename, mode );
32
                exit(-1);
33
        };
34
        if(log_level < 0)
35
            DCLogSetLevel( dclog, UCHAR_MAX );
36
        else
37
            DCLogSetLevel( dclog, log_level );
38
        DCLogSetHeader( dclog, 1 );
39
        DCLogSetPrintLevel( dclog, 1 );
40

    
41
        logstream = open_memstream(&logbuffer, &logbuffer_size);
42
        if (!logstream) {
43
                fprintf(stderr, "Unable to initialize logger, exiting");
44
                exit(-1);
45
        }
46
        initialized = 1;
47
}
48

    
49
void grapesCloseLog() {
50
        if (!initialized) return;
51

    
52
        DCLogClose(dclog);
53
        if (logstream) fclose(logstream);
54
        if (logbuffer) free(logbuffer);
55
        initialized = 0;
56
}
57

    
58
void grapesWriteLog(const unsigned char lev, const char *fmt, ... ) {
59
        va_list str_args;
60

    
61
        if (!initialized) return;
62

    
63
        rewind(logstream);
64

    
65
          va_start( str_args, fmt );
66
          if (vfprintf( logstream, fmt, str_args ) < 0) return;
67
          va_end( str_args );
68

    
69
        char zero = 0;
70
        if (fwrite(&zero, 1, 1, logstream) != 1) return;
71
        fflush(logstream);
72

    
73
        DCLogWrite(dclog, lev , logbuffer);
74
}
75