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