Towards 2.1.44. Bump copyright year.
[yaz-moved-to-github.git] / src / log.c
1 /*
2  * Copyright (C) 1995-2007, Index Data ApS
3  * See the file LICENSE for details.
4  *
5  * $Id: log.c,v 1.45 2007-01-03 08:42:15 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
180 #ifdef WIN32
181     /* windows can't rename a file if it is open */
182     yaz_log_close();
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 (yaz_file_type != use_file)
305         return;
306
307     if (l_fname && *l_fname)
308     {
309         strftime(new_filename, sizeof(new_filename)-1, l_fname, tm);
310         if (strcmp(new_filename, cur_filename))
311         {
312             strcpy(cur_filename, new_filename);
313             force = 1;
314         }
315     }
316
317     if (l_max_size > 0 && yaz_global_log_file)
318     {
319         long flen = ftell(yaz_global_log_file);
320         if (flen > l_max_size)
321         {
322             rotate_log(cur_filename);
323             force = 1;
324         }
325     }
326     if (force && *cur_filename)
327     {
328         FILE *new_file;
329 #ifdef WIN32
330         yaz_log_close();
331 #endif
332         new_file = fopen(cur_filename, filemode);
333         if (new_file)
334         {
335             yaz_log_close();
336             yaz_global_log_file = new_file;
337             if (l_level & YLOG_FLUSH)
338                 setvbuf(yaz_global_log_file, 0, _IONBF, 0);
339         }
340         else
341         {
342             /* disable log rotate */
343             l_max_size = 0;
344         }
345     }
346 }
347
348 static void yaz_log_do_reopen(const char *filemode)
349 {
350     time_t cur_time = time(0);
351 #if HAVE_LOCALTIME_R
352     struct tm tm0, *tm = &tm0;
353 #else
354     struct tm *tm;
355 #endif
356
357     nmem_mutex_enter(log_mutex);
358 #if HAVE_LOCALTIME_R
359     localtime_r(&cur_time, tm);
360 #else
361     tm = localtime(&cur_time);
362 #endif
363     yaz_log_open_check(tm, 1, filemode);
364     nmem_mutex_leave(log_mutex);
365 }
366
367
368 void yaz_log_reopen()
369 {
370     yaz_log_do_reopen("a");
371 }
372
373 void yaz_log_trunc()
374 {
375     yaz_log_do_reopen("w");
376 }
377
378
379
380 static void yaz_strftime(char *dst, size_t sz,
381                          const char *fmt, const struct tm *tm)
382 {
383     const char *cp = strstr(fmt, "%!");
384     if (cp && strlen(fmt) < 60)
385     {
386         char fmt2[80];
387         char tpidstr[20];
388 #ifdef WIN32
389         DWORD tid = GetCurrentThreadId();
390 #else
391         long tid = 0;
392 #if YAZ_POSIX_THREADS
393         tid = pthread_self();
394 #endif
395 #endif
396         memcpy(fmt2, fmt, cp-fmt);
397         fmt2[cp-fmt] = '\0';
398         sprintf(tpidstr, "%08lx", (long) tid);
399         strcat(fmt2, tpidstr);
400         strcat(fmt2, cp+2);
401         strftime(dst, sz, fmt2, tm);     
402     }
403     else
404         strftime(dst, sz, fmt, tm);
405 }
406                             
407 static void yaz_log_to_file(int level, const char *log_message)
408 {
409     FILE *file;
410     time_t ti = time(0);
411 #if HAVE_LOCALTIME_R
412     struct tm tm0, *tm = &tm0;
413 #else
414     struct tm *tm;
415 #endif
416
417     internal_log_init();
418
419     nmem_mutex_enter(log_mutex);
420     
421 #if HAVE_LOCALTIME_R
422     localtime_r(&ti, tm);
423 #else
424     tm = localtime(&ti);
425 #endif
426     
427     yaz_log_open_check(tm, 0, "a");  
428     file = yaz_log_file(); /* file may change in yaz_log_open_check */
429
430     if (file)
431     {
432         char tbuf[TIMEFORMAT_LEN];
433         char flags[1024];
434         int i;
435         
436         *flags = '\0';
437         for (i = 0; level && mask_names[i].name; i++)
438             if ( mask_names[i].mask & level)
439             {
440                 if (*mask_names[i].name && mask_names[i].mask && 
441                     mask_names[i].mask != YLOG_ALL)
442                 {
443                     sprintf(flags + strlen(flags), "[%s]", mask_names[i].name);
444                     level &= ~mask_names[i].mask;
445                 }
446             }
447         
448         if (l_level & YLOG_NOTIME)
449             tbuf[0] = '\0';
450         else
451             yaz_strftime(tbuf, TIMEFORMAT_LEN-1, l_actual_format, tm);
452         tbuf[TIMEFORMAT_LEN-1] = '\0';
453         
454         fprintf(file, "%s %s%s %s%s\n", tbuf, l_prefix, flags, l_prefix2,
455                 log_message);
456         if (l_level & YLOG_FLUSH)
457             fflush(file);
458     }
459     nmem_mutex_leave(log_mutex);
460 }
461
462 void yaz_log(int level, const char *fmt, ...)
463 {
464     va_list ap;
465     char buf[4096];
466     FILE *file;
467     int o_level = level;
468
469     internal_log_init();
470     if (!(level & l_level))
471         return;
472     va_start(ap, fmt);
473 #ifdef WIN32
474     _vsnprintf(buf, sizeof(buf)-1, fmt, ap);
475 #else
476 /* !WIN32 */
477 #if HAVE_VSNPRINTF
478     vsnprintf(buf, sizeof(buf), fmt, ap);
479 #else
480     vsprintf(buf, fmt, ap);
481 #endif
482 #endif
483 /* WIN32 */
484     if (o_level & YLOG_ERRNO)
485     {
486         strcat(buf, " [");
487         yaz_strerror(buf+strlen(buf), 2048);
488         strcat(buf, "]");
489     }
490     va_end (ap);
491     if (start_hook_func)
492         (*start_hook_func)(o_level, buf, start_hook_info);
493     if (hook_func)
494         (*hook_func)(o_level, buf, hook_info);
495     file = yaz_log_file();
496     if (file)
497         yaz_log_to_file(level, buf);
498     if (end_hook_func)
499         (*end_hook_func)(o_level, buf, end_hook_info);
500 }
501
502 void yaz_log_time_format(const char *fmt)
503 {
504     if ( !fmt || !*fmt) 
505     { /* no format, default to new */
506         l_actual_format = l_new_default_format;
507         return; 
508     }
509     if (0==strcmp(fmt, "old"))
510     { /* force the old format */
511         l_actual_format = l_old_default_format;
512         return; 
513     }
514     /* else use custom format */
515     strncpy(l_custom_format, fmt, TIMEFORMAT_LEN-1);
516     l_custom_format[TIMEFORMAT_LEN-1] = '\0';
517     l_actual_format = l_custom_format;
518 }
519
520 /** cleans a loglevel name from leading paths and suffixes */
521 static char *clean_name(const char *name, int len, char *namebuf, int buflen)
522 {
523     char *p = namebuf;
524     char *start = namebuf;
525     if (buflen <= len)
526         len = buflen-1; 
527     strncpy(namebuf, name, len);
528     namebuf[len] = '\0';
529     while ((p = strchr(start, '/')))
530         start = p+1;
531     if ((p = strrchr(start, '.')))
532         *p = '\0';
533     return start;
534 }
535
536 static int define_module_bit(const char *name)
537 {
538     int i;
539
540     nmem_mutex_enter(log_mutex);
541     for (i = 0; mask_names[i].name; i++)
542         if (0 == strcmp(mask_names[i].name, name))
543         {
544             nmem_mutex_leave(log_mutex);
545             return mask_names[i].mask;
546         }
547     if ( (i>=MAX_MASK_NAMES) || (next_log_bit & (1<<31) ))
548     {
549         nmem_mutex_leave(log_mutex);
550         yaz_log(YLOG_WARN, "No more log bits left, not logging '%s'", name);
551         return 0;
552     }
553     mask_names[i].mask = next_log_bit;
554     next_log_bit = next_log_bit<<1;
555     mask_names[i].name = malloc(strlen(name)+1);
556     strcpy(mask_names[i].name, name);
557     mask_names[i+1].name = NULL;
558     mask_names[i+1].mask = 0;
559     nmem_mutex_leave(log_mutex);
560     return mask_names[i].mask;
561 }
562
563 int yaz_log_module_level(const char *name)
564 {
565     int i;
566     char clean[255];
567     char *n = clean_name(name, strlen(name), clean, sizeof(clean));
568     internal_log_init();
569     
570     nmem_mutex_enter(log_mutex);
571     for (i = 0; mask_names[i].name; i++)
572         if (0==strcmp(n, mask_names[i].name))
573         {
574             nmem_mutex_leave(log_mutex);
575             yaz_log(YLOG_LOGLVL, "returning log bit 0x%x for '%s' %s",
576                     mask_names[i].mask, n, 
577                     strcmp(n,name) ? name : "");
578             return mask_names[i].mask;
579         }
580     nmem_mutex_leave(log_mutex);
581     yaz_log(YLOG_LOGLVL, "returning NO log bit for '%s' %s", n, 
582             strcmp(n, name) ? name : "" );
583     return 0;
584 }
585
586 int yaz_log_mask_str(const char *str)
587 {
588     internal_log_init(); /* since l_level may be affected */
589     return yaz_log_mask_str_x(str, l_level);
590 }
591
592 int yaz_log_mask_str_x(const char *str, int level)
593 {
594     const char *p;
595
596     internal_log_init();
597     while (*str)
598     {
599         int negated = 0;
600         for (p = str; *p && *p != ','; p++)
601             ;
602         if (*str=='-')
603         {
604             negated = 1;
605             str++;
606         }
607         if (isdigit(*(unsigned char *) str))
608         {
609             level = atoi(str);
610         }
611         else 
612         {
613             char clean[509];
614             char *n = clean_name(str, p-str, clean, sizeof(clean));
615             int mask = define_module_bit(n);
616             if (!mask)
617                 level = 0;  /* 'none' clears them all */
618             else if (negated)
619                 level &= ~mask;
620             else
621                 level |= mask;
622         }
623         if (*p == ',')
624             p++;
625         str = p;
626     }
627     return level;
628 }
629 /*
630  * Local variables:
631  * c-basic-offset: 4
632  * indent-tabs-mode: nil
633  * End:
634  * vim: shiftwidth=4 tabstop=8 expandtab
635  */