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