Fix mistake: fuzzy matching is 5=103, not 5=102
[yaz-moved-to-github.git] / src / log.c
1 /*
2  * Copyright (C) 1995-2006, Index Data ApS
3  * See the file LICENSE for details.
4  *
5  * $Id: log.c,v 1.35 2006-05-07 18:26:25 adam Exp $
6  */
7
8 /**
9  * \file log.c
10  * \brief 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
46 #if HAS_STRERROR
47
48 #else
49 char *strerror(int n)
50 {
51     extern char *sys_errlist[];
52     return sys_errlist[n];
53 }
54
55 #endif
56
57
58 static int default_log_level() {
59     char *env = getenv("YAZ_LOG");
60     if (env != 0)
61         return yaz_log_mask_str_x(env, YLOG_DEFAULT_LEVEL);
62     else
63         return YLOG_DEFAULT_LEVEL;
64 }
65
66
67 static int l_level = -1;        /* will be set from default_log_level() */
68
69 enum l_file_type {  use_stderr, use_none, use_file };
70 static enum l_file_type yaz_file_type = use_stderr;
71 static FILE *yaz_global_log_file = NULL;
72
73 static void (*start_hook_func)(int, const char *, void *) = NULL;
74 static void *start_hook_info;
75
76 static void (*end_hook_func)(int, const char *, void *) = NULL;
77 static void *end_hook_info;
78
79 static void (*hook_func)(int, const char *, void *) = NULL;
80 static void *hook_info;
81
82 static char l_prefix[512] = "";
83 static char l_prefix2[512] = "";
84 static char l_fname[512] = "";
85
86
87 static char l_old_default_format[] = "%H:%M:%S-%d/%m";
88 static char l_new_default_format[] = "%Y%m%d-%H%M%S";
89 #define TIMEFORMAT_LEN 50
90 static char l_custom_format[TIMEFORMAT_LEN] = "";
91 static char *l_actual_format = l_old_default_format;
92
93 /** l_max_size tells when to rotate the log. Default to 1 GB */
94 static const int l_def_max_size = 1024*1024*1024;
95 static int l_max_size = 1024*1024*1024;
96
97 #define MAX_MASK_NAMES 35   /* 32 bits plus a few combo names */
98 static struct {
99     int mask;
100     char *name;
101 } mask_names[MAX_MASK_NAMES] =
102 {
103     { YLOG_FATAL,  "fatal"},
104     { YLOG_DEBUG,  "debug"},
105     { YLOG_WARN,   "warn" },
106     { YLOG_LOG,    "log"  },
107     { YLOG_ERRNO,  ""},
108     { YLOG_MALLOC, "malloc"},
109     { YLOG_APP,    "app"  },
110     { YLOG_NOTIME, "notime" },
111     { YLOG_APP2,   "app2" }, 
112     { YLOG_APP3,   "app3" },
113     { YLOG_ALL,    "all"  },
114     { YLOG_FLUSH,  "flush" },
115     { YLOG_LOGLVL, "loglevel" }, 
116     { 0,           "none" },
117     { 0, NULL }
118     /* the rest will be filled in if the user defines dynamic modules*/
119 };  
120
121 static unsigned int next_log_bit = YLOG_LAST_BIT<<1; /* first dynamic bit */
122
123 static void init_mutex()
124 {
125     if (mutex_init_flag)
126         return;
127     nmem_mutex_create(&log_mutex);
128     mutex_init_flag = 1;
129 }
130
131 FILE *yaz_log_file(void)
132 {
133     FILE *f = 0;
134     switch(yaz_file_type)
135     {
136         case use_stderr: f = stderr; break;
137         case use_none: f = 0; break;
138         case use_file: f = yaz_global_log_file; break;
139     }
140     return f;
141 }
142
143 void yaz_log_close()
144 {
145     if (yaz_file_type == use_file && yaz_global_log_file)
146     {
147         fclose(yaz_global_log_file);
148         yaz_global_log_file = 0;
149     }
150 }
151
152 void yaz_log_init_file(const char *fname)
153 {
154     init_mutex();
155
156     yaz_log_close();
157     if (fname)
158     {
159         if (*fname == '\0')
160             yaz_file_type = use_stderr; /* empty name; use stderr */
161         else
162             yaz_file_type = use_file;
163         strncpy(l_fname, fname, sizeof(l_fname)-1);
164         l_fname[sizeof(l_fname)-1] = '\0';
165     }
166     else
167     {
168         yaz_file_type = use_none;  /* NULL name; use no file at all */
169         l_fname[0] = '\0'; 
170     }
171     yaz_log_reopen();
172 }
173
174 static void rotate_log(const char *cur_fname)
175 {
176     char newname[512];
177     strncpy(newname, cur_fname, 509);
178     newname[509] = '\0'; /* make sure it is terminated */
179     strcat(newname, ".1");
180 #ifdef WIN32
181     /* windows can't rename a file if it is open */
182     fclose(yaz_global_log_file);
183     yaz_global_log_file = 0;
184     MoveFileEx(cur_fname, newname, MOVEFILE_REPLACE_EXISTING);
185 #else
186     rename(cur_fname, newname);
187 #endif
188 }
189
190 void yaz_log_init_level(int level)
191 {
192     init_mutex();
193     if (l_level < 0) l_level = default_log_level();
194     if ( (l_level & YLOG_FLUSH) != (level & YLOG_FLUSH) )
195     {
196         l_level = level;
197         yaz_log_reopen(); /* make sure we set buffering right */
198     } else
199         l_level = level;
200     if (l_level  & YLOG_LOGLVL)
201     {  /* dump the log level bits */
202         const char *bittype = "Static ";
203         int i, sz;
204
205         yaz_log(YLOG_LOGLVL, "Setting log level to %d = 0x%08x",
206                 l_level, l_level);
207         /* determine size of mask_names (locked) */
208         nmem_mutex_enter(log_mutex);
209         for (sz = 0; mask_names[sz].name; sz++)
210             ;
211         nmem_mutex_leave(log_mutex);
212         /* second pass without lock */
213         for (i = 0; i < sz; i++)
214             if (mask_names[i].mask && *mask_names[i].name)
215                 if (strcmp(mask_names[i].name, "all") != 0)
216                 {
217                     yaz_log(YLOG_LOGLVL, "%s log bit %08x '%s' is %s",
218                             bittype, mask_names[i].mask, mask_names[i].name,
219                             (level & mask_names[i].mask)?  "ON": "off");
220                     if (mask_names[i].mask > YLOG_LAST_BIT)
221                         bittype = "Dynamic";
222                 }
223     }
224 }
225
226 void yaz_log_init_prefix(const char *prefix)
227 {
228     if (prefix && *prefix)
229         sprintf(l_prefix, "%.511s ", prefix);
230     else
231         *l_prefix = 0;
232 }
233
234 void yaz_log_init_prefix2(const char *prefix)
235 {
236     if (prefix && *prefix)
237         sprintf(l_prefix2, "%.511s ", prefix);
238     else
239         *l_prefix2 = 0;
240 }
241
242 void yaz_log_init(int level, const char *prefix, const char *fname)
243 {
244     init_mutex();
245     yaz_log_init_level(level);
246     yaz_log_init_prefix(prefix);
247     if (fname && *fname)
248         yaz_log_init_file(fname);
249 }
250
251 void yaz_log_init_max_size(int mx)
252 {
253     if (mx <0)
254         l_max_size = l_def_max_size;
255     else
256         l_max_size = mx;
257 }
258
259 void yaz_log_set_handler(void (*func)(int, const char *, void *), void *info)
260 {
261     hook_func = func;
262     hook_info = info;
263 }
264
265 void log_event_start(void (*func)(int, const char *, void *), void *info)
266 {
267      start_hook_func = func;
268      start_hook_info = info;
269 }
270
271 void log_event_end(void (*func)(int, const char *, void *), void *info)
272 {
273      end_hook_func = func;
274      end_hook_info = info;
275 }
276
277 static void yaz_log_open_check(struct tm *tm, int force)
278 {
279     char new_filename[512];
280     static char cur_filename[512] = "";
281
282     if (l_fname && *l_fname)
283     {
284         strftime(new_filename, sizeof(new_filename)-1, l_fname, tm);
285         if (strcmp(new_filename, cur_filename))
286         {
287             strcpy(cur_filename, new_filename);
288             force = 1;
289         }
290     }
291
292     if (l_max_size > 0 && yaz_global_log_file && yaz_file_type == use_file)
293     {
294         long flen = ftell(yaz_global_log_file);
295         if (flen > l_max_size)
296         {
297             rotate_log(cur_filename);
298             force = 1;
299         }
300     }
301     if (force && yaz_file_type == use_file && *cur_filename)
302     {
303         yaz_log_close();
304         yaz_global_log_file = fopen(cur_filename, "a");
305         if (l_level < 0) l_level = default_log_level();
306         if (l_level & YLOG_FLUSH)
307             setvbuf(yaz_global_log_file, 0, _IONBF, 0);
308     }
309 }
310
311 void yaz_log_reopen()
312 {
313     time_t cur_time = time(0);
314 #if HAVE_LOCALTIME_R
315     struct tm tm0, *tm = &tm0;
316 #else
317     struct tm *tm;
318 #endif
319
320     nmem_mutex_enter(log_mutex);
321 #if HAVE_LOCALTIME_R
322     localtime_r(&cur_time, tm);
323 #else
324     tm = localtime(&cur_time);
325 #endif
326     yaz_log_open_check(tm, 1);
327     nmem_mutex_leave(log_mutex);
328 }
329
330 static void yaz_strftime(char *dst, size_t sz,
331                          const char *fmt, const struct tm *tm)
332 {
333     const char *cp = strstr(fmt, "%!");
334     if (cp && strlen(fmt) < 60)
335     {
336         char fmt2[80];
337         char tpidstr[20];
338 #ifdef WIN32
339         DWORD tid = GetCurrentThreadId();
340 #else
341         long tid = 0;
342 #endif
343         memcpy(fmt2, fmt, cp-fmt);
344         fmt2[cp-fmt] = '\0';
345         sprintf(tpidstr, "%08lx", (long) tid);
346         strcat(fmt2, tpidstr);
347         strcat(fmt2, cp+2);
348         strftime(dst, sz, fmt2, tm);     
349     }
350     else
351         strftime(dst, sz, fmt, tm);
352 }
353                             
354 static void yaz_log_to_file(int level, FILE *file, const char *buf)
355 {
356     time_t ti = time(0);
357     int i;
358 #if HAVE_LOCALTIME_R
359     struct tm tm0, *tm = &tm0;
360 #else
361     struct tm *tm;
362 #endif
363
364     init_mutex();
365
366     nmem_mutex_enter(log_mutex);
367
368     #if HAVE_LOCALTIME_R
369     localtime_r(&ti, tm);
370 #else
371     tm = localtime(&ti);
372 #endif
373     
374     yaz_log_open_check(tm, 0);  
375     file = yaz_log_file(); /* file may change in yaz_log_open_check */
376
377     if (file)
378     {
379         char tbuf[TIMEFORMAT_LEN];
380         char flags[1024];
381         
382         *flags = '\0';
383         for (i = 0; level && mask_names[i].name; i++)
384             if ( mask_names[i].mask & level)
385             {
386                 if (*mask_names[i].name && mask_names[i].mask && 
387                     mask_names[i].mask != YLOG_ALL)
388                 {
389                     sprintf(flags + strlen(flags), "[%s]", mask_names[i].name);
390                     level &= ~mask_names[i].mask;
391                 }
392             }
393         
394         if (l_level & YLOG_NOTIME)
395             tbuf[0] = '\0';
396         else
397             yaz_strftime(tbuf, TIMEFORMAT_LEN-1, l_actual_format, tm);
398         tbuf[TIMEFORMAT_LEN-1] = '\0';
399         
400         fprintf(file, "%s %s%s %s%s\n", tbuf, l_prefix, flags, l_prefix2, buf);
401         if (l_level & (YLOG_FLUSH|YLOG_DEBUG) )
402             fflush(file);
403     }
404     nmem_mutex_leave(log_mutex);
405 }
406
407 void yaz_log(int level, const char *fmt, ...)
408 {
409     va_list ap;
410     char buf[4096];
411     FILE *file;
412     int o_level = level;
413
414     if (l_level < 0)
415         l_level = default_log_level();
416     if (!(level & l_level))
417         return;
418     va_start(ap, fmt);
419 #ifdef WIN32
420     _vsnprintf(buf, sizeof(buf)-1, fmt, ap);
421 #else
422 /* !WIN32 */
423 #if HAVE_VSNPRINTF
424     vsnprintf(buf, sizeof(buf), fmt, ap);
425 #else
426     vsprintf(buf, fmt, ap);
427 #endif
428 #endif
429 /* WIN32 */
430     if (o_level & YLOG_ERRNO)
431     {
432         strcat(buf, " [");
433         yaz_strerror(buf+strlen(buf), 2048);
434         strcat(buf, "]");
435     }
436     va_end (ap);
437     if (start_hook_func)
438         (*start_hook_func)(o_level, buf, start_hook_info);
439     if (hook_func)
440         (*hook_func)(o_level, buf, hook_info);
441     file = yaz_log_file();
442     if (file)
443         yaz_log_to_file(level, file, buf);
444     if (end_hook_func)
445         (*end_hook_func)(o_level, buf, end_hook_info);
446 }
447
448 void yaz_log_time_format(const char *fmt)
449 {
450     if ( !fmt || !*fmt) 
451     { /* no format, default to new */
452         l_actual_format = l_new_default_format;
453         return; 
454     }
455     if (0==strcmp(fmt, "old"))
456     { /* force the old format */
457         l_actual_format = l_old_default_format;
458         return; 
459     }
460     /* else use custom format */
461     strncpy(l_custom_format, fmt, TIMEFORMAT_LEN-1);
462     l_custom_format[TIMEFORMAT_LEN-1] = '\0';
463     l_actual_format = l_custom_format;
464 }
465
466 /** cleans a loglevel name from leading paths and suffixes */
467 static char *clean_name(const char *name, int len, char *namebuf, int buflen)
468 {
469     char *p = namebuf;
470     char *start = namebuf;
471     if (buflen <= len)
472         len = buflen-1; 
473     strncpy(namebuf, name, len);
474     namebuf[len] = '\0';
475     while ((p = strchr(start, '/')))
476         start = p+1;
477     if ((p = strrchr(start, '.')))
478         *p = '\0';
479     return start;
480 }
481
482 static int define_module_bit(const char *name)
483 {
484     int i;
485     init_mutex();
486     nmem_mutex_enter(log_mutex);
487     for (i = 0; mask_names[i].name; i++)
488         if (0 == strcmp(mask_names[i].name, name))
489         {
490             nmem_mutex_leave(log_mutex);
491             return mask_names[i].mask;
492         }
493     if ( (i>=MAX_MASK_NAMES) || (next_log_bit >= 1<<31 ))
494     {
495         nmem_mutex_leave(log_mutex);
496         yaz_log(YLOG_WARN, "No more log bits left, not logging '%s'", name);
497         return 0;
498     }
499     mask_names[i].mask = next_log_bit;
500     next_log_bit = next_log_bit<<1;
501     mask_names[i].name = malloc(strlen(name)+1);
502     strcpy(mask_names[i].name, name);
503     mask_names[i+1].name = NULL;
504     mask_names[i+1].mask = 0;
505     nmem_mutex_leave(log_mutex);
506     return mask_names[i].mask;
507 }
508
509 int yaz_log_module_level(const char *name)
510 {
511     int i;
512     char clean[255];
513     char *n = clean_name(name, strlen(name), clean, sizeof(clean));
514     init_mutex();
515     
516     nmem_mutex_enter(log_mutex);
517     for (i = 0; mask_names[i].name; i++)
518         if (0==strcmp(n, mask_names[i].name))
519         {
520             nmem_mutex_leave(log_mutex);
521             yaz_log(YLOG_LOGLVL, "returning log bit 0x%x for '%s' %s",
522                     mask_names[i].mask, n, 
523                     strcmp(n,name) ? name : "");
524             return mask_names[i].mask;
525         }
526     nmem_mutex_leave(log_mutex);
527     yaz_log(YLOG_LOGLVL, "returning NO log bit for '%s' %s", n, 
528                     strcmp(n, name) ? name : "" );
529     return 0;
530 }
531
532 int yaz_log_mask_str(const char *str)
533 {
534     return yaz_log_mask_str_x(str, default_log_level());
535 }
536
537 int yaz_log_mask_str_x(const char *str, int level)
538 {
539     const char *p;
540
541     while (*str)
542     {
543         int negated = 0;
544         for (p = str; *p && *p != ','; p++)
545             ;
546         if (*str=='-')
547         {
548             negated = 1;
549             str++;
550         }
551         if (isdigit(*(unsigned char *) str))
552         {
553             level = atoi(str);
554         }
555         else 
556         {
557             char clean[509];
558             char *n = clean_name(str, p-str, clean, sizeof(clean));
559             int mask = define_module_bit(n);
560             if (!mask)
561                 level = 0;  /* 'none' clears them all */
562             else if (negated)
563                 level &= ~mask;
564             else
565                 level |= mask;
566         }
567         if (*p == ',')
568             p++;
569         str = p;
570     }
571     return level;
572 }
573 /*
574  * Local variables:
575  * c-basic-offset: 4
576  * indent-tabs-mode: nil
577  * End:
578  * vim: shiftwidth=4 tabstop=8 expandtab
579  */