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