Happy new year
[yaz-moved-to-github.git] / src / log.c
1 /* This file is part of the YAZ toolkit.
2  * Copyright (C) 1995-2009 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/nmem.h>
31 #include <yaz/log.h>
32 #include <yaz/snprintf.h>
33 #include <yaz/xmalloc.h>
34
35 #define HAS_STRERROR 1
36
37
38 #if HAS_STRERROR
39
40 #else
41 char *strerror(int n)
42 {
43     extern char *sys_errlist[];
44     return sys_errlist[n];
45 }
46
47 #endif
48
49
50 static int l_level = YLOG_DEFAULT_LEVEL;
51
52 enum l_file_type { use_stderr, use_none, use_file };
53 static enum l_file_type yaz_file_type = use_stderr;
54 static FILE *yaz_global_log_file = NULL;
55
56 static void (*start_hook_func)(int, const char *, void *) = NULL;
57 static void *start_hook_info;
58
59 static void (*end_hook_func)(int, const char *, void *) = NULL;
60 static void *end_hook_info;
61
62 static void (*hook_func)(int, const char *, void *) = NULL;
63 static void *hook_info;
64
65 static char l_prefix[512] = "";
66 static char l_prefix2[512] = "";
67 static char l_fname[512] = "";
68
69
70 static char l_old_default_format[] = "%H:%M:%S-%d/%m";
71 static char l_new_default_format[] = "%Y%m%d-%H%M%S";
72 #define TIMEFORMAT_LEN 50
73 static char l_custom_format[TIMEFORMAT_LEN] = "";
74 static char *l_actual_format = l_old_default_format;
75
76 /** l_max_size tells when to rotate the log. Default is 1 GB 
77     This is almost the same as never, but it saves applications in the
78     case of 2 or 4 GB file size limits..
79  */
80 static int l_max_size = 1024*1024*1024;
81
82 #define MAX_MASK_NAMES 35   /* 32 bits plus a few combo names */
83 static struct {
84     int mask;
85     char *name;
86 } mask_names[MAX_MASK_NAMES] =
87 {
88     { YLOG_FATAL,  "fatal"},
89     { YLOG_DEBUG,  "debug"},
90     { YLOG_WARN,   "warn" },
91     { YLOG_LOG,    "log"  },
92     { YLOG_ERRNO,  ""},
93     { YLOG_MALLOC, "malloc"},
94     { YLOG_APP,    "app"  },
95     { YLOG_NOTIME, "notime" },
96     { YLOG_APP2,   "app2" }, 
97     { YLOG_APP3,   "app3" },
98     { YLOG_ALL,    "all"  },
99     { YLOG_FLUSH,  "flush" },
100     { YLOG_LOGLVL, "loglevel" }, 
101     { 0,           "none" },
102     { 0, NULL }
103     /* the rest will be filled in if the user defines dynamic modules*/
104 };  
105
106 static unsigned int next_log_bit = YLOG_LAST_BIT<<1; /* first dynamic bit */
107
108 static void internal_log_init(void)
109 {
110     static int mutex_init_flag = 0; /* not yet initialized */
111     char *env;
112
113     if (mutex_init_flag)
114         return;
115     mutex_init_flag = 1; /* here, 'cause nmem_mutex_create may call yaz_log */
116
117     env = getenv("YAZ_LOG");
118     if (env)
119         l_level = yaz_log_mask_str_x(env, l_level);
120 }
121
122
123 FILE *yaz_log_file(void)
124 {
125     FILE *f = 0;
126     switch(yaz_file_type)
127     {
128         case use_stderr: f = stderr; break;
129         case use_none: f = 0; break;
130         case use_file: f = yaz_global_log_file; break;
131     }
132     return f;
133 }
134
135 void yaz_log_close(void)
136 {
137     if (yaz_file_type == use_file && yaz_global_log_file)
138     {
139         fclose(yaz_global_log_file);
140         yaz_global_log_file = 0;
141     }
142 }
143
144 void yaz_log_init_file(const char *fname)
145 {
146     internal_log_init();
147
148     yaz_log_close();
149     if (fname)
150     {
151         if (*fname == '\0')
152             yaz_file_type = use_stderr; /* empty name; use stderr */
153         else
154             yaz_file_type = use_file;
155         strncpy(l_fname, fname, sizeof(l_fname)-1);
156         l_fname[sizeof(l_fname)-1] = '\0';
157     }
158     else
159     {
160         yaz_file_type = use_none;  /* NULL name; use no file at all */
161         l_fname[0] = '\0'; 
162     }
163     yaz_log_reopen();
164 }
165
166 static void rotate_log(const char *cur_fname)
167 {
168     int i;
169
170 #ifdef WIN32
171     /* windows can't rename a file if it is open */
172     yaz_log_close();
173 #endif
174     for (i = 0; i<9; i++)
175     {
176         char fname_str[FILENAME_MAX];
177         struct stat stat_buf;
178
179         yaz_snprintf(fname_str, sizeof(fname_str), "%s.%d", cur_fname, i);
180         if (stat(fname_str, &stat_buf) != 0)
181             break;
182     }
183     for (; i >= 0; --i)
184     {
185         char fname_str[2][FILENAME_MAX];
186
187         if (i > 0)
188             yaz_snprintf(fname_str[0], sizeof(fname_str[0]),
189                          "%s.%d", cur_fname, i-1);
190         else
191             yaz_snprintf(fname_str[0], sizeof(fname_str[0]),
192                          "%s", cur_fname);
193         yaz_snprintf(fname_str[1], sizeof(fname_str[1]),
194                      "%s.%d", cur_fname, i);
195 #ifdef WIN32
196         MoveFileEx(fname_str[0], fname_str[1], MOVEFILE_REPLACE_EXISTING);
197 #else
198         rename(fname_str[0], fname_str[1]);
199 #endif
200     }
201 }
202
203
204 void yaz_log_init_level(int level)
205 {
206     internal_log_init();
207     if ( (l_level & YLOG_FLUSH) != (level & YLOG_FLUSH) )
208     {
209         l_level = level;
210         yaz_log_reopen(); /* make sure we set buffering right */
211     } 
212     else
213         l_level = level;
214
215     if (l_level  & YLOG_LOGLVL)
216     {  /* dump the log level bits */
217         const char *bittype = "Static ";
218         int i, sz;
219
220         yaz_log(YLOG_LOGLVL, "Setting log level to %d = 0x%08x",
221                 l_level, l_level);
222         /* determine size of mask_names (locked) */
223         for (sz = 0; mask_names[sz].name; sz++)
224             ;
225         /* second pass without lock */
226         for (i = 0; i < sz; i++)
227             if (mask_names[i].mask && *mask_names[i].name)
228                 if (strcmp(mask_names[i].name, "all") != 0)
229                 {
230                     yaz_log(YLOG_LOGLVL, "%s log bit %08x '%s' is %s",
231                             bittype, mask_names[i].mask, mask_names[i].name,
232                             (level & mask_names[i].mask)?  "ON": "off");
233                     if (mask_names[i].mask > YLOG_LAST_BIT)
234                         bittype = "Dynamic";
235                 }
236     }
237 }
238
239 void yaz_log_init_prefix(const char *prefix)
240 {
241     if (prefix && *prefix)
242         yaz_snprintf(l_prefix, sizeof(l_prefix), "%s ", prefix);
243     else
244         *l_prefix = 0;
245 }
246
247 void yaz_log_init_prefix2(const char *prefix)
248 {
249     if (prefix && *prefix)
250         yaz_snprintf(l_prefix2, sizeof(l_prefix2), "%s ", prefix);
251     else
252         *l_prefix2 = 0;
253 }
254
255 void yaz_log_init(int level, const char *prefix, const char *fname)
256 {
257     internal_log_init();
258     yaz_log_init_level(level);
259     yaz_log_init_prefix(prefix);
260     if (fname && *fname)
261         yaz_log_init_file(fname);
262 }
263
264 void yaz_log_init_max_size(int mx)
265 {
266     if (mx > 0)
267         l_max_size = mx;
268     else
269         l_max_size = 0;
270 }
271
272 void yaz_log_set_handler(void (*func)(int, const char *, void *), void *info)
273 {
274     hook_func = func;
275     hook_info = info;
276 }
277
278 void log_event_start(void (*func)(int, const char *, void *), void *info)
279 {
280      start_hook_func = func;
281      start_hook_info = info;
282 }
283
284 void log_event_end(void (*func)(int, const char *, void *), void *info)
285 {
286      end_hook_func = func;
287      end_hook_info = info;
288 }
289
290 static void yaz_log_open_check(struct tm *tm, int force, const char *filemode)
291 {
292     char new_filename[512];
293     static char cur_filename[512] = "";
294
295     if (yaz_file_type != use_file)
296         return;
297
298     if (*l_fname)
299     {
300         strftime(new_filename, sizeof(new_filename)-1, l_fname, 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_global_log_file)
309     {
310         long flen = ftell(yaz_global_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_global_log_file = new_file;
328             if (l_level & YLOG_FLUSH)
329                 setvbuf(yaz_global_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 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         fprintf(file, "%s%s%s %s%s\n", tbuf, l_prefix, flags, l_prefix2,
427                 log_message);
428         if (l_level & YLOG_FLUSH)
429             fflush(file);
430     }
431 }
432
433 void yaz_log(int level, const char *fmt, ...)
434 {
435     va_list ap;
436     char buf[4096];
437     FILE *file;
438     int o_level = level;
439
440     internal_log_init();
441     if (!(level & l_level))
442         return;
443     va_start(ap, fmt);
444
445     /* 30 is enough for our 'rest of output' message */
446     yaz_vsnprintf(buf, sizeof(buf)-30, fmt, ap);
447     if (strlen(buf) >= sizeof(buf)-31)
448         strcat(buf, " [rest of output omitted]");
449
450     if (o_level & YLOG_ERRNO)
451     {
452         int remain = sizeof(buf) - strlen(buf);
453         if (remain > 100) /* reasonable minimum space for error */
454         {
455             strcat(buf, " [");
456             yaz_strerror(buf+strlen(buf), remain-5); /* 5 due to extra [] */
457             strcat(buf, "]");
458         }
459     }
460     va_end (ap);
461     if (start_hook_func)
462         (*start_hook_func)(o_level, buf, start_hook_info);
463     if (hook_func)
464         (*hook_func)(o_level, buf, hook_info);
465     file = yaz_log_file();
466     if (file)
467         yaz_log_to_file(level, buf);
468     if (end_hook_func)
469         (*end_hook_func)(o_level, buf, end_hook_info);
470 }
471
472 void yaz_log_time_format(const char *fmt)
473 {
474     if ( !fmt || !*fmt) 
475     { /* no format, default to new */
476         l_actual_format = l_new_default_format;
477         return; 
478     }
479     if (0==strcmp(fmt, "old"))
480     { /* force the old format */
481         l_actual_format = l_old_default_format;
482         return; 
483     }
484     /* else use custom format */
485     strncpy(l_custom_format, fmt, TIMEFORMAT_LEN-1);
486     l_custom_format[TIMEFORMAT_LEN-1] = '\0';
487     l_actual_format = l_custom_format;
488 }
489
490 /** cleans a loglevel name from leading paths and suffixes */
491 static char *clean_name(const char *name, int len, char *namebuf, int buflen)
492 {
493     char *p = namebuf;
494     char *start = namebuf;
495     if (buflen <= len)
496         len = buflen-1; 
497     strncpy(namebuf, name, len);
498     namebuf[len] = '\0';
499     while ((p = strchr(start, '/')))
500         start = p+1;
501     if ((p = strrchr(start, '.')))
502         *p = '\0';
503     return start;
504 }
505
506 static int define_module_bit(const char *name)
507 {
508     int i;
509
510     for (i = 0; mask_names[i].name; i++)
511         if (0 == strcmp(mask_names[i].name, name))
512         {
513             return mask_names[i].mask;
514         }
515     if ( (i>=MAX_MASK_NAMES) || (next_log_bit & (1<<31) ))
516     {
517         yaz_log(YLOG_WARN, "No more log bits left, not logging '%s'", name);
518         return 0;
519     }
520     mask_names[i].mask = next_log_bit;
521     next_log_bit = next_log_bit<<1;
522     mask_names[i].name = (char *) malloc(strlen(name)+1);
523     strcpy(mask_names[i].name, name);
524     mask_names[i+1].name = NULL;
525     mask_names[i+1].mask = 0;
526     return mask_names[i].mask;
527 }
528
529 int yaz_log_module_level(const char *name)
530 {
531     int i;
532     char clean[255];
533     char *n = clean_name(name, strlen(name), clean, sizeof(clean));
534     internal_log_init();
535     
536     for (i = 0; mask_names[i].name; i++)
537         if (0==strcmp(n, mask_names[i].name))
538         {
539             yaz_log(YLOG_LOGLVL, "returning log bit 0x%x for '%s' %s",
540                     mask_names[i].mask, n, 
541                     strcmp(n,name) ? name : "");
542             return mask_names[i].mask;
543         }
544     yaz_log(YLOG_LOGLVL, "returning NO log bit for '%s' %s", n, 
545             strcmp(n, name) ? name : "" );
546     return 0;
547 }
548
549 int yaz_log_mask_str(const char *str)
550 {
551     internal_log_init(); /* since l_level may be affected */
552     return yaz_log_mask_str_x(str, l_level);
553 }
554
555 int yaz_log_mask_str_x(const char *str, int level)
556 {
557     const char *p;
558
559     internal_log_init();
560     while (*str)
561     {
562         int negated = 0;
563         for (p = str; *p && *p != ','; p++)
564             ;
565         if (*str=='-')
566         {
567             negated = 1;
568             str++;
569         }
570         if (isdigit(*(unsigned char *) str))
571         {
572             level = atoi(str);
573         }
574         else 
575         {
576             char clean[509];
577             char *n = clean_name(str, p-str, clean, sizeof(clean));
578             int mask = define_module_bit(n);
579             if (!mask)
580                 level = 0;  /* 'none' clears them all */
581             else if (negated)
582                 level &= ~mask;
583             else
584                 level |= mask;
585         }
586         if (*p == ',')
587             p++;
588         str = p;
589     }
590     return level;
591 }
592 /*
593  * Local variables:
594  * c-basic-offset: 4
595  * indent-tabs-mode: nil
596  * End:
597  * vim: shiftwidth=4 tabstop=8 expandtab
598  */