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