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