Statistics
| Branch: | Revision:

napa-baselibs / dclog / log.c @ 507372bb

History | View | Annotate | Download (2.19 KB)

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

    
5
#define _GNU_SOURCE
6

    
7
#include        <stdio.h>
8
#include        <stdlib.h>
9
#include        <stdarg.h>
10
#include        <napa_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 napaInitLog(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
#if !WIN32 && !MAC_OS
42
        logstream = open_memstream(&logbuffer, &logbuffer_size);
43
        if (!logstream) {
44
                fprintf(stderr, "Unable to initialize logger, exiting");
45
                exit(-1);
46
        }
47
#else
48
        logbuffer_size=1000;
49
        logbuffer = (char *) malloc(logbuffer_size);
50
#endif
51
        initialized = 1;
52
}
53

    
54
void napaCloseLog() {
55
        if (!initialized) return;
56

    
57
        DCLogClose(dclog);
58
        if (logstream) fclose(logstream);
59
        if (logbuffer) free(logbuffer);
60
        initialized = 0;
61
}
62

    
63
void napaWriteLog(const unsigned char lev, const char *fmt, ... ) {
64
        va_list str_args;
65

    
66
        if (!initialized) return;
67

    
68

    
69
          va_start( str_args, fmt );
70
#if !WIN32 && !MAC_OS
71
        rewind(logstream);
72
          if (vfprintf( logstream, fmt, str_args ) < 0) return;
73
        char zero = 0;
74
        if (fwrite(&zero, 1, 1, logstream) != 1) return;
75
        fflush(logstream);
76
#else
77
        if (vsnprintf( logbuffer, logbuffer_size, fmt, str_args) < 0) return;
78
        logbuffer[logbuffer_size - 1] = '\0';
79
#endif
80
          va_end( str_args );
81

    
82
//fprintf(stderr, "X.do logger lev:%d, msg %s\n", lev, logbuffer);
83
        DCLogWrite(dclog, lev , logbuffer);
84
        fflush(dclog->fp);
85
}
86