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