Get rid of redundant parameter to yaz_log_to_file. Reformat a bit
[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.38 2006-07-31 10:05:04 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() {
59     char *env = getenv("YAZ_LOG");
60     if (env != 0)
61         return yaz_log_mask_str_x(env, YLOG_DEFAULT_LEVEL);
62     else
63         return YLOG_DEFAULT_LEVEL;
64 }
65
66
67 static int l_level = -1;        /* will be set from default_log_level() */
68
69 enum l_file_type {  use_stderr, use_none, use_file };
70 static enum l_file_type yaz_file_type = use_stderr;
71 static FILE *yaz_global_log_file = NULL;
72
73 static void (*start_hook_func)(int, const char *, void *) = NULL;
74 static void *start_hook_info;
75
76 static void (*end_hook_func)(int, const char *, void *) = NULL;
77 static void *end_hook_info;
78
79 static void (*hook_func)(int, const char *, void *) = NULL;
80 static void *hook_info;
81
82 static char l_prefix[512] = "";
83 static char l_prefix2[512] = "";
84 static char l_fname[512] = "";
85
86
87 static char l_old_default_format[] = "%H:%M:%S-%d/%m";
88 static char l_new_default_format[] = "%Y%m%d-%H%M%S";
89 #define TIMEFORMAT_LEN 50
90 static char l_custom_format[TIMEFORMAT_LEN] = "";
91 static char *l_actual_format = l_old_default_format;
92
93 /** l_max_size tells when to rotate the log. Default to 1 GB */
94 static const int l_def_max_size = 1024*1024*1024;
95 static int l_max_size = 1024*1024*1024;
96
97 #define MAX_MASK_NAMES 35   /* 32 bits plus a few combo names */
98 static struct {
99     int mask;
100     char *name;
101 } mask_names[MAX_MASK_NAMES] =
102 {
103     { YLOG_FATAL,  "fatal"},
104     { YLOG_DEBUG,  "debug"},
105     { YLOG_WARN,   "warn" },
106     { YLOG_LOG,    "log"  },
107     { YLOG_ERRNO,  ""},
108     { YLOG_MALLOC, "malloc"},
109     { YLOG_APP,    "app"  },
110     { YLOG_NOTIME, "notime" },
111     { YLOG_APP2,   "app2" }, 
112     { YLOG_APP3,   "app3" },
113     { YLOG_ALL,    "all"  },
114     { YLOG_FLUSH,  "flush" },
115     { YLOG_LOGLVL, "loglevel" }, 
116     { 0,           "none" },
117     { 0, NULL }
118     /* the rest will be filled in if the user defines dynamic modules*/
119 };  
120
121 static unsigned int next_log_bit = YLOG_LAST_BIT<<1; /* first dynamic bit */
122
123 static void init_mutex()
124 {
125     if (mutex_init_flag)
126         return;
127     nmem_mutex_create(&log_mutex);
128     mutex_init_flag = 1;
129 }
130
131 FILE *yaz_log_file(void)
132 {
133     FILE *f = 0;
134     switch(yaz_file_type)
135     {
136         case use_stderr: f = stderr; break;
137         case use_none: f = 0; break;
138         case use_file: f = yaz_global_log_file; break;
139     }
140     return f;
141 }
142
143 void yaz_log_close()
144 {
145     if (yaz_file_type == use_file && yaz_global_log_file)
146     {
147         fclose(yaz_global_log_file);
148         yaz_global_log_file = 0;
149     }
150 }
151
152 void yaz_log_init_file(const char *fname)
153 {
154     init_mutex();
155
156     yaz_log_close();
157     if (fname)
158     {
159         if (*fname == '\0')
160             yaz_file_type = use_stderr; /* empty name; use stderr */
161         else
162             yaz_file_type = use_file;
163         strncpy(l_fname, fname, sizeof(l_fname)-1);
164         l_fname[sizeof(l_fname)-1] = '\0';
165     }
166     else
167     {
168         yaz_file_type = use_none;  /* NULL name; use no file at all */
169         l_fname[0] = '\0'; 
170     }
171     yaz_log_reopen();
172 }
173
174 static void rotate_log(const char *cur_fname)
175 {
176     char newname[512];
177     strncpy(newname, cur_fname, 509);
178     newname[509] = '\0'; /* make sure it is terminated */
179     strcat(newname, ".1");
180 #ifdef WIN32
181     /* windows can't rename a file if it is open */
182     fclose(yaz_global_log_file);
183     yaz_global_log_file = 0;
184     MoveFileEx(cur_fname, newname, MOVEFILE_REPLACE_EXISTING);
185 #else
186     rename(cur_fname, newname);
187 #endif
188 }
189
190
191 void yaz_log_init_level(int level)
192 {
193     init_mutex();
194     if (l_level < 0) 
195         l_level = default_log_level();
196     if ( (l_level & YLOG_FLUSH) != (level & YLOG_FLUSH) )
197     {
198         l_level = level;
199         yaz_log_reopen(); /* make sure we set buffering right */
200     } 
201     else
202         l_level = level;
203     if (l_level  & YLOG_LOGLVL)
204     {  /* dump the log level bits */
205         const char *bittype = "Static ";
206         int i, sz;
207
208         yaz_log(YLOG_LOGLVL, "Setting log level to %d = 0x%08x",
209                 l_level, l_level);
210         /* determine size of mask_names (locked) */
211         nmem_mutex_enter(log_mutex);
212         for (sz = 0; mask_names[sz].name; sz++)
213             ;
214         nmem_mutex_leave(log_mutex);
215         /* second pass without lock */
216         for (i = 0; i < sz; i++)
217             if (mask_names[i].mask && *mask_names[i].name)
218                 if (strcmp(mask_names[i].name, "all") != 0)
219                 {
220                     yaz_log(YLOG_LOGLVL, "%s log bit %08x '%s' is %s",
221                             bittype, mask_names[i].mask, mask_names[i].name,
222                             (level & mask_names[i].mask)?  "ON": "off");
223                     if (mask_names[i].mask > YLOG_LAST_BIT)
224                         bittype = "Dynamic";
225                 }
226     }
227 }
228
229 void yaz_log_init_prefix(const char *prefix)
230 {
231     if (prefix && *prefix)
232         sprintf(l_prefix, "%.511s ", prefix);
233     else
234         *l_prefix = 0;
235 }
236
237 void yaz_log_init_prefix2(const char *prefix)
238 {
239     if (prefix && *prefix)
240         sprintf(l_prefix2, "%.511s ", prefix);
241     else
242         *l_prefix2 = 0;
243 }
244
245 void yaz_log_init(int level, const char *prefix, const char *fname)
246 {
247     init_mutex();
248     yaz_log_init_level(level);
249     yaz_log_init_prefix(prefix);
250     if (fname && *fname)
251         yaz_log_init_file(fname);
252 }
253
254 void yaz_log_init_max_size(int mx)
255 {
256     if (mx <0)
257         l_max_size = l_def_max_size;
258     else
259         l_max_size = mx;
260 }
261
262 void yaz_log_set_handler(void (*func)(int, const char *, void *), void *info)
263 {
264     hook_func = func;
265     hook_info = info;
266 }
267
268 void log_event_start(void (*func)(int, const char *, void *), void *info)
269 {
270      start_hook_func = func;
271      start_hook_info = info;
272 }
273
274 void log_event_end(void (*func)(int, const char *, void *), void *info)
275 {
276      end_hook_func = func;
277      end_hook_info = info;
278 }
279
280 static void yaz_log_open_check(struct tm *tm, int force, const char *filemode)
281 {
282     char new_filename[512];
283     static char cur_filename[512] = "";
284
285     if (l_fname && *l_fname)
286     {
287         strftime(new_filename, sizeof(new_filename)-1, l_fname, tm);
288         if (strcmp(new_filename, cur_filename))
289         {
290             strcpy(cur_filename, new_filename);
291             force = 1;
292         }
293     }
294
295     if (l_max_size > 0 && yaz_global_log_file && yaz_file_type == use_file)
296     {
297         long flen = ftell(yaz_global_log_file);
298         if (flen > l_max_size)
299         {
300             rotate_log(cur_filename);
301             force = 1;
302         }
303     }
304     if (force && yaz_file_type == use_file && *cur_filename)
305     {
306         yaz_log_close();
307         yaz_global_log_file = fopen(cur_filename, filemode);
308         if (l_level < 0) l_level = default_log_level();
309         if (l_level & YLOG_FLUSH)
310             setvbuf(yaz_global_log_file, 0, _IONBF, 0);
311     }
312 }
313
314 static void yaz_log_do_reopen(const char *filemode)
315 {
316     time_t cur_time = time(0);
317 #if HAVE_LOCALTIME_R
318     struct tm tm0, *tm = &tm0;
319 #else
320     struct tm *tm;
321 #endif
322
323     nmem_mutex_enter(log_mutex);
324 #if HAVE_LOCALTIME_R
325     localtime_r(&cur_time, tm);
326 #else
327     tm = localtime(&cur_time);
328 #endif
329     yaz_log_open_check(tm, 1, filemode);
330     nmem_mutex_leave(log_mutex);
331 }
332
333
334 void yaz_log_reopen()
335 {
336     yaz_log_do_reopen("a");
337 }
338
339 void yaz_log_trunc()
340 {
341     yaz_log_do_reopen("w");
342 }
343
344
345
346 static void yaz_strftime(char *dst, size_t sz,
347                          const char *fmt, const struct tm *tm)
348 {
349     const char *cp = strstr(fmt, "%!");
350     if (cp && strlen(fmt) < 60)
351     {
352         char fmt2[80];
353         char tpidstr[20];
354 #ifdef WIN32
355         DWORD tid = GetCurrentThreadId();
356 #else
357         long tid = 0;
358 #if YAZ_POSIX_THREADS
359         tid = pthread_self();
360 #endif
361 #endif
362         memcpy(fmt2, fmt, cp-fmt);
363         fmt2[cp-fmt] = '\0';
364         sprintf(tpidstr, "%08lx", (long) tid);
365         strcat(fmt2, tpidstr);
366         strcat(fmt2, cp+2);
367         strftime(dst, sz, fmt2, tm);     
368     }
369     else
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     init_mutex();
384
385     nmem_mutex_enter(log_mutex);
386     
387 #if HAVE_LOCALTIME_R
388     localtime_r(&ti, tm);
389 #else
390     tm = localtime(&ti);
391 #endif
392     
393     yaz_log_open_check(tm, 0, "a");  
394     file = yaz_log_file(); /* file may change in yaz_log_open_check */
395
396     if (file)
397     {
398         char tbuf[TIMEFORMAT_LEN];
399         char flags[1024];
400         int i;
401         
402         *flags = '\0';
403         for (i = 0; level && mask_names[i].name; i++)
404             if ( mask_names[i].mask & level)
405             {
406                 if (*mask_names[i].name && mask_names[i].mask && 
407                     mask_names[i].mask != YLOG_ALL)
408                 {
409                     sprintf(flags + strlen(flags), "[%s]", mask_names[i].name);
410                     level &= ~mask_names[i].mask;
411                 }
412             }
413         
414         if (l_level & YLOG_NOTIME)
415             tbuf[0] = '\0';
416         else
417             yaz_strftime(tbuf, TIMEFORMAT_LEN-1, l_actual_format, tm);
418         tbuf[TIMEFORMAT_LEN-1] = '\0';
419         
420         fprintf(file, "%s %s%s %s%s\n", tbuf, l_prefix, flags, l_prefix2,
421                 log_message);
422         if (l_level & (YLOG_FLUSH|YLOG_DEBUG) )
423             fflush(file);
424     }
425     nmem_mutex_leave(log_mutex);
426 }
427
428 void yaz_log(int level, const char *fmt, ...)
429 {
430     va_list ap;
431     char buf[4096];
432     FILE *file;
433     int o_level = level;
434
435     if (l_level < 0)
436         l_level = default_log_level();
437     if (!(level & l_level))
438         return;
439     va_start(ap, fmt);
440 #ifdef WIN32
441     _vsnprintf(buf, sizeof(buf)-1, fmt, ap);
442 #else
443 /* !WIN32 */
444 #if HAVE_VSNPRINTF
445     vsnprintf(buf, sizeof(buf), fmt, ap);
446 #else
447     vsprintf(buf, fmt, ap);
448 #endif
449 #endif
450 /* WIN32 */
451     if (o_level & YLOG_ERRNO)
452     {
453         strcat(buf, " [");
454         yaz_strerror(buf+strlen(buf), 2048);
455         strcat(buf, "]");
456     }
457     va_end (ap);
458     if (start_hook_func)
459         (*start_hook_func)(o_level, buf, start_hook_info);
460     if (hook_func)
461         (*hook_func)(o_level, buf, hook_info);
462     file = yaz_log_file();
463     if (file)
464         yaz_log_to_file(level, buf);
465     if (end_hook_func)
466         (*end_hook_func)(o_level, buf, end_hook_info);
467 }
468
469 void yaz_log_time_format(const char *fmt)
470 {
471     if ( !fmt || !*fmt) 
472     { /* no format, default to new */
473         l_actual_format = l_new_default_format;
474         return; 
475     }
476     if (0==strcmp(fmt, "old"))
477     { /* force the old format */
478         l_actual_format = l_old_default_format;
479         return; 
480     }
481     /* else use custom format */
482     strncpy(l_custom_format, fmt, TIMEFORMAT_LEN-1);
483     l_custom_format[TIMEFORMAT_LEN-1] = '\0';
484     l_actual_format = l_custom_format;
485 }
486
487 /** cleans a loglevel name from leading paths and suffixes */
488 static char *clean_name(const char *name, int len, char *namebuf, int buflen)
489 {
490     char *p = namebuf;
491     char *start = namebuf;
492     if (buflen <= len)
493         len = buflen-1; 
494     strncpy(namebuf, name, len);
495     namebuf[len] = '\0';
496     while ((p = strchr(start, '/')))
497         start = p+1;
498     if ((p = strrchr(start, '.')))
499         *p = '\0';
500     return start;
501 }
502
503 static int define_module_bit(const char *name)
504 {
505     int i;
506     init_mutex();
507     nmem_mutex_enter(log_mutex);
508     for (i = 0; mask_names[i].name; i++)
509         if (0 == strcmp(mask_names[i].name, name))
510         {
511             nmem_mutex_leave(log_mutex);
512             return mask_names[i].mask;
513         }
514     if ( (i>=MAX_MASK_NAMES) || (next_log_bit >= 1<<31 ))
515     {
516         nmem_mutex_leave(log_mutex);
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 = 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     nmem_mutex_leave(log_mutex);
527     return mask_names[i].mask;
528 }
529
530 int yaz_log_module_level(const char *name)
531 {
532     int i;
533     char clean[255];
534     char *n = clean_name(name, strlen(name), clean, sizeof(clean));
535     init_mutex();
536     
537     nmem_mutex_enter(log_mutex);
538     for (i = 0; mask_names[i].name; i++)
539         if (0==strcmp(n, mask_names[i].name))
540         {
541             nmem_mutex_leave(log_mutex);
542             yaz_log(YLOG_LOGLVL, "returning log bit 0x%x for '%s' %s",
543                     mask_names[i].mask, n, 
544                     strcmp(n,name) ? name : "");
545             return mask_names[i].mask;
546         }
547     nmem_mutex_leave(log_mutex);
548     yaz_log(YLOG_LOGLVL, "returning NO log bit for '%s' %s", n, 
549                     strcmp(n, name) ? name : "" );
550     return 0;
551 }
552
553 int yaz_log_mask_str(const char *str)
554 {
555     return yaz_log_mask_str_x(str, default_log_level());
556 }
557
558 int yaz_log_mask_str_x(const char *str, int level)
559 {
560     const char *p;
561
562     while (*str)
563     {
564         int negated = 0;
565         for (p = str; *p && *p != ','; p++)
566             ;
567         if (*str=='-')
568         {
569             negated = 1;
570             str++;
571         }
572         if (isdigit(*(unsigned char *) str))
573         {
574             level = atoi(str);
575         }
576         else 
577         {
578             char clean[509];
579             char *n = clean_name(str, p-str, clean, sizeof(clean));
580             int mask = define_module_bit(n);
581             if (!mask)
582                 level = 0;  /* 'none' clears them all */
583             else if (negated)
584                 level &= ~mask;
585             else
586                 level |= mask;
587         }
588         if (*p == ',')
589             p++;
590         str = p;
591     }
592     return level;
593 }
594 /*
595  * Local variables:
596  * c-basic-offset: 4
597  * indent-tabs-mode: nil
598  * End:
599  * vim: shiftwidth=4 tabstop=8 expandtab
600  */