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