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