Fixed the infinite recursion when calling yaz_log_level_init as the first
[yaz-moved-to-github.git] / src / log.c
1 /*
2  * Copyright (C) 1995-2005, Index Data ApS
3  * See the file LICENSE for details.
4  *
5  * $Id: log.c,v 1.22 2005-04-29 10:36:05 heikki Exp $
6  */
7
8 /**
9  * \file log.c
10  * \brief Implements logging utility
11  */
12
13 #if HAVE_CONFIG_H
14 #include <config.h>
15 #endif
16
17 #ifdef WIN32
18 #include <windows.h>
19 #endif
20
21 #if YAZ_POSIX_THREADS
22 #include <pthread.h>
23 #endif
24
25 #if YAZ_GNU_THREADS
26 #include <pth.h>
27 #endif
28
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <ctype.h>
32 #include <string.h>
33 #include <stdarg.h>
34 #include <errno.h>
35 #include <time.h>
36 #include <yaz/nmem.h>
37 #include <yaz/log.h>
38 #include <yaz/xmalloc.h>
39
40 static NMEM_MUTEX log_mutex = 0;
41 static int mutex_init_flag = 0; /* not yet initialized */
42
43 #define HAS_STRERROR 1
44
45 #if HAS_STRERROR
46
47 #else
48 char *strerror(int n)
49 {
50     extern char *sys_errlist[];
51     return sys_errlist[n];
52 }
53
54 #endif
55
56
57
58 static int l_level = YLOG_DEFAULT_LEVEL;
59 static FILE *l_file = NULL;
60 static char l_prefix[512] = "";
61 static char l_prefix2[512] = "";
62 static char l_fname[512] = "";
63
64 static char l_old_default_format[] = "%H:%M:%S-%d/%m";
65 static char l_new_default_format[] = "%Y%m%d-%H%M%S";
66 #define TIMEFORMAT_LEN 50
67 static char l_custom_format[TIMEFORMAT_LEN] = "";
68 static char *l_actual_format = l_old_default_format;
69
70 /** l_max_size tells when to rotate the log. Default to 1 GB */
71 static const int l_def_max_size = 1024*1024*1024;
72 static int l_max_size = 1024*1024*1024;
73
74 #define MAX_MASK_NAMES 35   /* 32 bits plus a few combo names */
75 static struct {
76     int mask;
77     char *name;
78 }  mask_names[MAX_MASK_NAMES] =
79 {
80     { YLOG_FATAL,  "fatal"},
81     { YLOG_DEBUG,  "debug"},
82     { YLOG_WARN,   "warn" },
83     { YLOG_LOG,    "log"  },
84     { YLOG_ERRNO,  ""},
85     { YLOG_MALLOC, "malloc"},
86  /*   { YLOG_APP,    "app"  }, */
87     { YLOG_NOTIME, "notime" },
88  /*   { YLOG_APP2,   "app2" }, */
89  /*   { YLOG_APP3,   "app3" }, */
90     { YLOG_ALL,    "all"  },
91     { YLOG_FLUSH,  "flush" },
92     { YLOG_LOGLVL, "loglevel" }, 
93     { 0,          "none" },
94     { 0, NULL }
95     /* the rest will be filled in if the user defines dynamic modules*/
96 };  
97 static unsigned int next_log_bit = YLOG_LAST_BIT<<1; /* first dynamic bit */
98
99 static void init_mutex()
100 {
101     if (mutex_init_flag)
102         return;
103     nmem_mutex_create (&log_mutex);
104     mutex_init_flag = 1;
105 }
106
107
108 FILE *yaz_log_file(void)
109 {
110     if (!l_file)
111         l_file = stderr;
112     return l_file;
113 }
114
115 void yaz_log_init_file (const char *fname)
116 {
117     if (!mutex_init_flag)
118         init_mutex();
119     if (fname)
120     {
121         strncpy(l_fname, fname, sizeof(l_fname)-1);
122         l_fname[sizeof(l_fname)-1] = '\0';
123     }
124     else
125         l_fname[0] = '\0';
126     yaz_log_reopen();
127 }
128
129 void yaz_log_reopen(void)
130 {
131     FILE *new_file;
132     if (!mutex_init_flag)
133         init_mutex();
134     if (!l_file)
135         l_file = stderr;
136     if (!*l_fname)
137         new_file = stderr;
138     else if (!(new_file = fopen(l_fname, "a")))
139     {
140         new_file=l_file;
141         l_file=stderr;  /* just to be sure we don't rotate logs and recurse */
142         yaz_log(YLOG_WARN|YLOG_ERRNO,"Could not open log file '%s'",l_fname);
143         l_file=new_file; /* restore to old value, probably stderr as well */
144         return;
145     }
146     if (l_file != stderr)
147     {
148         fclose (l_file);
149     }
150     if (l_level & YLOG_FLUSH)
151         setvbuf(new_file, 0, _IONBF, 0);
152     l_file = new_file;
153 }
154
155 static void rotate_log()
156 {
157     char newname[512];
158     if (l_file==stderr)
159         return; /* can't rotate that */
160     if (!*l_fname)
161         return; /* hmm, no name, can't rotate */
162     strncpy(newname, l_fname, 509);
163     newname[509] = '\0'; /* make sure it is terminated */
164     strcat(newname,".1");
165 #ifdef WIN32
166     /* windows can't rename a file if it is open */
167     fclose(l_file);
168     l_file = stderr;
169 #endif
170     rename(l_fname, newname);
171     yaz_log_reopen();
172 }
173
174
175 void yaz_log_init_level (int level)
176 {
177     if (!mutex_init_flag)
178         init_mutex();
179     if ( (l_level & YLOG_FLUSH) != (level & YLOG_FLUSH) )
180     {
181         l_level = level;
182         yaz_log_reopen(); /* make sure we set buffering right */
183     } else
184         l_level = level;
185     if (l_level  & YLOG_LOGLVL)
186     {  /* dump the log level bits */
187         char *bittype="Static ";
188         int i;
189         yaz_log(YLOG_LOGLVL,"Setting log level to %d = 0x%08x",l_level,l_level);
190         for (i = 0; mask_names[i].name; i++)
191             if (mask_names[i].mask && *mask_names[i].name)
192                 if (strcmp(mask_names[i].name,"all")!=0)
193                 {
194                     yaz_log(YLOG_LOGLVL,"%s log bit %08x '%s' is %s",
195                         bittype, mask_names[i].mask, mask_names[i].name,
196                         (level & mask_names[i].mask)?  "ON": "off");
197                 if (mask_names[i].mask>YLOG_LAST_BIT)
198                     bittype="Dynamic";
199                 }
200     }
201 }
202
203 void yaz_log_init_prefix (const char *prefix)
204 {
205     if (prefix && *prefix)
206         sprintf(l_prefix, "%.511s ", prefix);
207     else
208         *l_prefix = 0;
209 }
210
211 void yaz_log_init_prefix2 (const char *prefix)
212 {
213     if (prefix && *prefix)
214         sprintf(l_prefix2, "%.511s ", prefix);
215     else
216         *l_prefix2 = 0;
217 }
218
219 void yaz_log_init(int level, const char *prefix, const char *fname)
220 {
221     if (!mutex_init_flag)
222         init_mutex();
223     yaz_log_init_level (level);
224     yaz_log_init_prefix (prefix);
225     if (fname && *fname)
226         yaz_log_init_file (fname);
227 }
228
229 void yaz_log_init_max_size(int mx)
230 {
231     if (mx <0)
232         l_max_size = l_def_max_size;
233     else
234         l_max_size = mx;
235 }
236
237 static void (*start_hook_func)(int, const char *, void *) = NULL;
238 static void *start_hook_info;
239 static void (*end_hook_func)(int, const char *, void *) = NULL;
240 static void *end_hook_info;
241
242 void log_event_start (void (*func)(int, const char *, void *), void *info)
243 {
244     start_hook_func = func;
245     start_hook_info = info;
246 }
247
248 void log_event_end (void (*func)(int, const char *, void *), void *info)
249 {
250     end_hook_func = func;
251     end_hook_info = info;
252 }
253
254 void yaz_log(int level, const char *fmt, ...)
255 {
256     va_list ap;
257     char buf[4096], flags[1024];
258     int i;
259     time_t ti;
260     struct tm *tim;
261     char tbuf[TIMEFORMAT_LEN] = "";
262     int o_level = level;
263     int flen; 
264
265     if (!(level & l_level))
266         return;
267     if (!mutex_init_flag)
268         init_mutex();
269     if (!l_file)
270         l_file = stderr;
271     
272     if ((l_file != stderr) && (l_max_size>0))
273     {
274         nmem_mutex_enter (log_mutex);
275         flen = ftell(l_file);
276         if (flen>l_max_size) 
277             rotate_log();
278         nmem_mutex_leave (log_mutex);
279     }
280
281     *flags = '\0';
282     for (i = 0; level && mask_names[i].name; i++)
283         if ( mask_names[i].mask & level)
284         {
285             if (*mask_names[i].name && mask_names[i].mask && 
286                  mask_names[i].mask != YLOG_ALL)
287             {
288                 sprintf(flags + strlen(flags), "[%s]", mask_names[i].name);
289                 level &= ~mask_names[i].mask;
290             }
291         }
292     va_start(ap, fmt);
293 #ifdef WIN32
294     _vsnprintf(buf, sizeof(buf)-1, fmt, ap);
295 #else
296 /* !WIN32 */
297 #if HAVE_VSNPRINTF
298     vsnprintf(buf, sizeof(buf), fmt, ap);
299 #else
300     vsprintf(buf, fmt, ap);
301 #endif
302 #endif
303 /* WIN32 */
304     if (o_level & YLOG_ERRNO)
305     {
306         strcat(buf, " [");
307         yaz_strerror(buf+strlen(buf), 2048);
308         strcat(buf, "]");
309     }
310     va_end (ap);
311     if (start_hook_func)
312         (*start_hook_func)(o_level, buf, start_hook_info);
313     ti = time(0);
314     tim = localtime(&ti);
315     if (l_level & YLOG_NOTIME)
316         tbuf[0] = '\0';
317     else
318         strftime(tbuf, TIMEFORMAT_LEN-1, l_actual_format, tim);
319     tbuf[TIMEFORMAT_LEN-1] = '\0';
320     fprintf(l_file, "%s %s%s %s%s\n", tbuf, l_prefix, flags,
321             l_prefix2, buf);
322     if (l_level & (YLOG_FLUSH|YLOG_DEBUG) )
323         fflush(l_file);
324     if (end_hook_func)
325         (*end_hook_func)(o_level, buf, end_hook_info);
326 }
327
328 void yaz_log_time_format(const char *fmt)
329 {
330     if ( !fmt || !*fmt) 
331     { /* no format, default to new */
332         l_actual_format = l_new_default_format;
333         return; 
334     }
335     if (0==strcmp(fmt,"old"))
336     { /* force the old format */
337         l_actual_format = l_old_default_format;
338         return; 
339     }
340     /* else use custom format */
341     strncpy(l_custom_format, fmt, TIMEFORMAT_LEN-1);
342     l_custom_format[TIMEFORMAT_LEN-1] = '\0';
343     l_actual_format = l_custom_format;
344 }
345
346 /** cleans a loglevel name from leading paths and suffixes */
347 static char *clean_name(const char *name, int len, char *namebuf, int buflen)
348 {
349     char *p = namebuf;
350     char *start = namebuf;
351     if (buflen <len)
352         len = buflen; 
353     strncpy(namebuf, name, len);
354     namebuf[len] = '\0';
355     while ((p = strchr(start,'/')))
356         start = p+1;
357     if ((p = strrchr(start,'.')))
358         *p = '\0';
359     return start;
360
361 }
362
363 static int define_module_bit(const char *name)
364 {
365     int i;
366     if (!mutex_init_flag)
367         init_mutex();
368     for (i = 0; mask_names[i].name; i++)
369         ;
370     if ( (i>=MAX_MASK_NAMES) || (next_log_bit >= 1<<31 ))
371     {
372         yaz_log(YLOG_WARN,"No more log bits left, not logging '%s'", name);
373         return 0;
374     }
375     mask_names[i].mask = next_log_bit;
376     next_log_bit = next_log_bit<<1;
377     mask_names[i].name = xstrdup(name);
378     mask_names[i+1].name = NULL;
379     mask_names[i+1].mask = 0;
380     return mask_names[i].mask;
381 }
382
383 int yaz_log_module_level(const char *name)
384 {
385     int i;
386     char clean[255];
387     char *n = clean_name(name, strlen(name), clean, sizeof(clean));
388     if (!mutex_init_flag)
389         init_mutex();
390     for (i = 0; mask_names[i].name; i++)
391         if (0==strcmp(n,mask_names[i].name))
392         {
393             yaz_log(YLOG_LOGLVL,"returning log bit 0x%x for '%s' %s",
394                     mask_names[i].mask, n, 
395                     strcmp(n,name)?name:"" );
396             return mask_names[i].mask;
397         }
398     yaz_log(YLOG_LOGLVL,"returning NO log bit for '%s' %s", n, 
399                     strcmp(n,name)?name:"" );
400     return 0;
401 }
402
403 int yaz_log_mask_str (const char *str)
404 {
405     return yaz_log_mask_str_x (str, YLOG_DEFAULT_LEVEL);
406 }
407
408 int yaz_log_mask_str_x (const char *str, int level)
409 {
410     const char *p;
411     int i;
412     char clean[255] = "";
413     char *n = clean;
414
415     while (*str)
416     {
417         int found = 0;
418         int negated = 0;
419         for (p = str; *p && *p != ','; p++)
420             ;
421         if (*str=='-')
422         {
423             negated=1;
424             str++;
425         }
426         if (isdigit(*(unsigned char *) str))
427         {
428             level = atoi (str);
429             found = 1;
430         }
431         else 
432         {
433             n = clean_name(str, p-str, clean, sizeof(clean));
434             for (i = 0; mask_names[i].name; i++)
435                 if (0==strcmp (mask_names[i].name,n))
436                 {
437                     if (mask_names[i].mask)
438                         if (negated)
439                             level &= ~mask_names[i].mask;
440                         else
441                             level |= mask_names[i].mask;
442                     else
443                         level = 0; /* 'none' clears them all */
444                     found = 1;
445                 }
446         }
447         if (!found)
448             level |= define_module_bit(n);
449         if (*p == ',')
450             p++;
451         str = p;
452     }
453     return level;
454 }