Remove log_event_{start,end}. Add function yaz_log_set_handler instead
[yaz-moved-to-github.git] / src / log.c
1 /*
2  * Copyright (C) 1995-2005, Index Data ApS
3  * See the file LICENSE for details.
4  *
5  * $Id: log.c,v 1.32 2006-03-21 12:54:02 adam Exp $
6  */
7
8 /**
9  * \file log.c
10  * \brief Implements 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 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 to 1 GB */
85 static const int l_def_max_size = 1024*1024*1024;
86 static int l_max_size = 1024*1024*1024;
87
88 #define MAX_MASK_NAMES 35   /* 32 bits plus a few combo names */
89 static struct {
90     int mask;
91     char *name;
92 } mask_names[MAX_MASK_NAMES] =
93 {
94     { YLOG_FATAL,  "fatal"},
95     { YLOG_DEBUG,  "debug"},
96     { YLOG_WARN,   "warn" },
97     { YLOG_LOG,    "log"  },
98     { YLOG_ERRNO,  ""},
99     { YLOG_MALLOC, "malloc"},
100     { YLOG_APP,    "app"  },
101     { YLOG_NOTIME, "notime" },
102     { YLOG_APP2,   "app2" }, 
103     { YLOG_APP3,   "app3" },
104     { YLOG_ALL,    "all"  },
105     { YLOG_FLUSH,  "flush" },
106     { YLOG_LOGLVL, "loglevel" }, 
107     { 0,           "none" },
108     { 0, NULL }
109     /* the rest will be filled in if the user defines dynamic modules*/
110 };  
111
112 static unsigned int next_log_bit = YLOG_LAST_BIT<<1; /* first dynamic bit */
113
114 static void init_mutex()
115 {
116     if (mutex_init_flag)
117         return;
118     nmem_mutex_create(&log_mutex);
119     mutex_init_flag = 1;
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()
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     init_mutex();
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     char newname[512];
168     strncpy(newname, cur_fname, 509);
169     newname[509] = '\0'; /* make sure it is terminated */
170     strcat(newname, ".1");
171 #ifdef WIN32
172     /* windows can't rename a file if it is open */
173     fclose(l_file);
174     l_file = 0;
175     MoveFileEx(cur_fname, newname, MOVEFILE_REPLACE_EXISTING);
176 #else
177     rename(cur_fname, newname);
178 #endif
179 }
180
181 void yaz_log_init_level(int level)
182 {
183     init_mutex();
184     if (l_level < 0) l_level = default_log_level();
185     if ( (l_level & YLOG_FLUSH) != (level & YLOG_FLUSH) )
186     {
187         l_level = level;
188         yaz_log_reopen(); /* make sure we set buffering right */
189     } else
190         l_level = level;
191     if (l_level  & YLOG_LOGLVL)
192     {  /* dump the log level bits */
193         const char *bittype = "Static ";
194         int i, sz;
195
196         yaz_log(YLOG_LOGLVL, "Setting log level to %d = 0x%08x",
197                 l_level, l_level);
198         /* determine size of mask_names (locked) */
199         nmem_mutex_enter(log_mutex);
200         for (sz = 0; mask_names[sz].name; sz++)
201             ;
202         nmem_mutex_leave(log_mutex);
203         /* second pass without lock */
204         for (i = 0; i < sz; i++)
205             if (mask_names[i].mask && *mask_names[i].name)
206                 if (strcmp(mask_names[i].name, "all") != 0)
207                 {
208                     yaz_log(YLOG_LOGLVL, "%s log bit %08x '%s' is %s",
209                             bittype, mask_names[i].mask, mask_names[i].name,
210                             (level & mask_names[i].mask)?  "ON": "off");
211                     if (mask_names[i].mask > YLOG_LAST_BIT)
212                         bittype = "Dynamic";
213                 }
214     }
215 }
216
217 void yaz_log_init_prefix(const char *prefix)
218 {
219     if (prefix && *prefix)
220         sprintf(l_prefix, "%.511s ", prefix);
221     else
222         *l_prefix = 0;
223 }
224
225 void yaz_log_init_prefix2(const char *prefix)
226 {
227     if (prefix && *prefix)
228         sprintf(l_prefix2, "%.511s ", prefix);
229     else
230         *l_prefix2 = 0;
231 }
232
233 void yaz_log_init(int level, const char *prefix, const char *fname)
234 {
235     init_mutex();
236     yaz_log_init_level(level);
237     yaz_log_init_prefix(prefix);
238     if (fname && *fname)
239         yaz_log_init_file(fname);
240 }
241
242 void yaz_log_init_max_size(int mx)
243 {
244     if (mx <0)
245         l_max_size = l_def_max_size;
246     else
247         l_max_size = mx;
248 }
249
250 static void (*hook_func)(int, const char *, void *) = NULL;
251 static void *hook_info;
252
253 void yaz_log_set_handler(void (*func)(int, const char *, void *), void *info)
254 {
255     hook_func = func;
256     hook_info = info;
257 }
258
259 static void yaz_log_open_check(struct tm *tm, int force)
260 {
261     char new_filename[512];
262     static char cur_filename[512] = "";
263
264     if (l_fname && *l_fname)
265     {
266         strftime(new_filename, sizeof(new_filename)-1, l_fname, tm);
267         if (strcmp(new_filename, cur_filename))
268         {
269             strcpy(cur_filename, new_filename);
270             force = 1;
271         }
272     }
273
274     if (l_max_size > 0 && yaz_global_log_file && yaz_file_type == use_file)
275     {
276         long flen = ftell(yaz_global_log_file);
277         if (flen > l_max_size)
278         {
279             rotate_log(cur_filename);
280             force = 1;
281         }
282     }
283     if (force && yaz_file_type == use_file && *cur_filename)
284     {
285         yaz_log_close();
286         yaz_global_log_file = fopen(cur_filename, "a");
287         if (l_level < 0) l_level = default_log_level();
288         if (l_level & YLOG_FLUSH)
289             setvbuf(yaz_global_log_file, 0, _IONBF, 0);
290     }
291 }
292
293 void yaz_log_reopen()
294 {
295     time_t cur_time = time(0);
296 #if HAVE_LOCALTIME_R
297     struct tm tm0, *tm = &tm0;
298 #else
299     struct tm *tm;
300 #endif
301
302     nmem_mutex_enter(log_mutex);
303 #if HAVE_LOCALTIME_R
304     localtime_r(&cur_time, tm);
305 #else
306     tm = localtime(&cur_time);
307 #endif
308     yaz_log_open_check(tm, 1);
309     nmem_mutex_leave(log_mutex);
310 }
311
312 static void yaz_log_to_file(int level, FILE *file, const char *buf)
313 {
314     time_t ti = time(0);
315     int i;
316 #if HAVE_LOCALTIME_R
317     struct tm tm0, *tm = &tm0;
318 #else
319     struct tm *tm;
320 #endif
321
322     init_mutex();
323
324     nmem_mutex_enter(log_mutex);
325
326     #if HAVE_LOCALTIME_R
327     localtime_r(&ti, tm);
328 #else
329     tm = localtime(&ti);
330 #endif
331     
332     yaz_log_open_check(tm, 0);  
333     file = yaz_log_file(); /* file may change in yaz_log_open_check */
334
335     if (file)
336     {
337         char tbuf[TIMEFORMAT_LEN];
338         char flags[1024];
339         
340         *flags = '\0';
341         for (i = 0; level && mask_names[i].name; i++)
342             if ( mask_names[i].mask & level)
343             {
344                 if (*mask_names[i].name && mask_names[i].mask && 
345                     mask_names[i].mask != YLOG_ALL)
346                 {
347                     sprintf(flags + strlen(flags), "[%s]", mask_names[i].name);
348                     level &= ~mask_names[i].mask;
349                 }
350             }
351         
352         if (l_level & YLOG_NOTIME)
353             tbuf[0] = '\0';
354         else
355             strftime(tbuf, TIMEFORMAT_LEN-1, l_actual_format, tm);
356         tbuf[TIMEFORMAT_LEN-1] = '\0';
357         
358         fprintf(file, "%s %s%s %s%s\n", tbuf, l_prefix, flags, l_prefix2, buf);
359         if (l_level & (YLOG_FLUSH|YLOG_DEBUG) )
360             fflush(file);
361     }
362     nmem_mutex_leave(log_mutex);
363 }
364
365 void yaz_log(int level, const char *fmt, ...)
366 {
367     va_list ap;
368     char buf[4096];
369     FILE *file;
370     int o_level = level;
371
372     if (l_level < 0)
373         l_level = default_log_level();
374     if (!(level & l_level))
375         return;
376     va_start(ap, fmt);
377 #ifdef WIN32
378     _vsnprintf(buf, sizeof(buf)-1, fmt, ap);
379 #else
380 /* !WIN32 */
381 #if HAVE_VSNPRINTF
382     vsnprintf(buf, sizeof(buf), fmt, ap);
383 #else
384     vsprintf(buf, fmt, ap);
385 #endif
386 #endif
387 /* WIN32 */
388     if (o_level & YLOG_ERRNO)
389     {
390         strcat(buf, " [");
391         yaz_strerror(buf+strlen(buf), 2048);
392         strcat(buf, "]");
393     }
394     va_end (ap);
395     if (hook_func)
396         (*hook_func)(o_level, buf, hook_info);
397
398     file = yaz_log_file();
399     if (file)
400         yaz_log_to_file(level, file, buf);
401 }
402
403 void yaz_log_time_format(const char *fmt)
404 {
405     if ( !fmt || !*fmt) 
406     { /* no format, default to new */
407         l_actual_format = l_new_default_format;
408         return; 
409     }
410     if (0==strcmp(fmt, "old"))
411     { /* force the old format */
412         l_actual_format = l_old_default_format;
413         return; 
414     }
415     /* else use custom format */
416     strncpy(l_custom_format, fmt, TIMEFORMAT_LEN-1);
417     l_custom_format[TIMEFORMAT_LEN-1] = '\0';
418     l_actual_format = l_custom_format;
419 }
420
421 /** cleans a loglevel name from leading paths and suffixes */
422 static char *clean_name(const char *name, int len, char *namebuf, int buflen)
423 {
424     char *p = namebuf;
425     char *start = namebuf;
426     if (buflen <= len)
427         len = buflen-1; 
428     strncpy(namebuf, name, len);
429     namebuf[len] = '\0';
430     while ((p = strchr(start, '/')))
431         start = p+1;
432     if ((p = strrchr(start, '.')))
433         *p = '\0';
434     return start;
435 }
436
437 static int define_module_bit(const char *name)
438 {
439     int i;
440     init_mutex();
441     nmem_mutex_enter(log_mutex);
442     for (i = 0; mask_names[i].name; i++)
443         if (0 == strcmp(mask_names[i].name, name))
444         {
445             nmem_mutex_leave(log_mutex);
446             return mask_names[i].mask;
447         }
448     if ( (i>=MAX_MASK_NAMES) || (next_log_bit >= 1<<31 ))
449     {
450         nmem_mutex_leave(log_mutex);
451         yaz_log(YLOG_WARN, "No more log bits left, not logging '%s'", name);
452         return 0;
453     }
454     mask_names[i].mask = next_log_bit;
455     next_log_bit = next_log_bit<<1;
456     mask_names[i].name = malloc(strlen(name)+1);
457     strcpy(mask_names[i].name, name);
458     mask_names[i+1].name = NULL;
459     mask_names[i+1].mask = 0;
460     nmem_mutex_leave(log_mutex);
461     return mask_names[i].mask;
462 }
463
464 int yaz_log_module_level(const char *name)
465 {
466     int i;
467     char clean[255];
468     char *n = clean_name(name, strlen(name), clean, sizeof(clean));
469     init_mutex();
470     
471     nmem_mutex_enter(log_mutex);
472     for (i = 0; mask_names[i].name; i++)
473         if (0==strcmp(n, mask_names[i].name))
474         {
475             nmem_mutex_leave(log_mutex);
476             yaz_log(YLOG_LOGLVL, "returning log bit 0x%x for '%s' %s",
477                     mask_names[i].mask, n, 
478                     strcmp(n,name) ? name : "");
479             return mask_names[i].mask;
480         }
481     nmem_mutex_leave(log_mutex);
482     yaz_log(YLOG_LOGLVL, "returning NO log bit for '%s' %s", n, 
483                     strcmp(n, name) ? name : "" );
484     return 0;
485 }
486
487 int yaz_log_mask_str(const char *str)
488 {
489     return yaz_log_mask_str_x(str, default_log_level());
490 }
491
492 int yaz_log_mask_str_x(const char *str, int level)
493 {
494     const char *p;
495
496     while (*str)
497     {
498         int negated = 0;
499         for (p = str; *p && *p != ','; p++)
500             ;
501         if (*str=='-')
502         {
503             negated = 1;
504             str++;
505         }
506         if (isdigit(*(unsigned char *) str))
507         {
508             level = atoi(str);
509         }
510         else 
511         {
512             char clean[509];
513             char *n = clean_name(str, p-str, clean, sizeof(clean));
514             int mask = define_module_bit(n);
515             if (!mask)
516                 level = 0;  /* 'none' clears them all */
517             else if (negated)
518                 level &= ~mask;
519             else
520                 level |= mask;
521         }
522         if (*p == ',')
523             p++;
524         str = p;
525     }
526     return level;
527 }
528 /*
529  * Local variables:
530  * c-basic-offset: 4
531  * indent-tabs-mode: nil
532  * End:
533  * vim: shiftwidth=4 tabstop=8 expandtab
534  */