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