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