]> git.imager.perl.org - imager.git/blob - log.c
fb08ffd4a91afb10bfe48f80eff2952a21631d78
[imager.git] / log.c
1 #include "imconfig.h"
2 #include "log.h"
3 #include <stdlib.h>
4
5 #define DTBUFF 50
6 #define DATABUFF DTBUFF+3+10+1+5+1+1
7
8 static int   log_level   = 0;
9 static FILE *lg_file     = NULL;
10 static char *date_format = "%Y/%m/%d %H:%M:%S";
11 static char  date_buffer[DTBUFF];
12 static char  data_buffer[DATABUFF];
13
14
15 #ifdef IMAGER_LOG
16
17 /*
18  * Logging is active
19  */
20
21 void
22 i_init_log(const char* name,int level) {
23   log_level = level;
24   if (level < 0) {
25     lg_file = NULL;
26   } else {
27     if (name == NULL) {
28       lg_file = stderr;
29     } else {
30       if (NULL == (lg_file = fopen(name, "w+")) ) { 
31         fprintf(stderr,"Cannot open file '%s'\n",name);
32         exit(2);
33       }
34     }
35   }
36   setvbuf(lg_file, NULL, _IONBF, BUFSIZ);
37   mm_log((0,"Imager - log started (level = %d)\n", level));
38 }
39
40 void
41 i_fatal(int exitcode,const char *fmt, ... ) {
42   va_list ap;
43   time_t timi;
44   struct tm *str_tm;
45   
46   if (lg_file != NULL) {
47     timi = time(NULL);
48     str_tm = localtime(&timi);
49     if ( strftime(date_buffer, DTBUFF, date_format, str_tm) )
50       fprintf(lg_file,"[%s] ",date_buffer);
51     va_start(ap,fmt);
52     vfprintf(lg_file,fmt,ap);
53     va_end(ap);
54   }
55   exit(exitcode);
56 }
57
58 #else
59
60 /*
61  * Logging is inactive - insert dummy functions
62  */
63
64 void i_init_log(const char* name,int onoff) {}
65 void i_fatal(int exitcode,const char *fmt, ... ) { exit(exitcode); }
66
67
68 #endif
69
70
71 void
72 i_loog(int level,const char *fmt, ... ) {
73   va_list ap;
74   if (level > log_level) return;
75   if (lg_file != NULL) {
76     fputs(data_buffer, lg_file);
77     fprintf(lg_file, "%3d: ",level);
78     va_start(ap,fmt);
79     vfprintf(lg_file, fmt, ap);
80     fflush(lg_file);
81     va_end(ap);
82   }
83 }
84
85
86 void
87 i_lhead(const char *file, int line) {
88   time_t timi;
89   struct tm *str_tm;
90   
91   if (lg_file != NULL) {
92     timi = time(NULL);
93     str_tm = localtime(&timi);
94     strftime(date_buffer, DTBUFF, date_format, str_tm);
95     sprintf(data_buffer, "[%s] %10s:%-5d ", date_buffer, file, line);
96   }
97 }