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