0bb27e7665b36e1e85930154024bc0370734810c
[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.31 2006-03-21 12:31:48 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 (*start_hook_func)(int, const char *, void *) = NULL;
251 static void *start_hook_info;
252 static void (*end_hook_func)(int, const char *, void *) = NULL;
253 static void *end_hook_info;
254
255 void log_event_start(void (*func)(int, const char *, void *), void *info)
256 {
257     start_hook_func = func;
258     start_hook_info = info;
259 }
260
261 void log_event_end(void (*func)(int, const char *, void *), void *info)
262 {
263     end_hook_func = func;
264     end_hook_info = info;
265 }
266
267 static void yaz_log_open_check(struct tm *tm, int force)
268 {
269     char new_filename[512];
270     static char cur_filename[512] = "";
271
272     if (l_fname && *l_fname)
273     {
274         strftime(new_filename, sizeof(new_filename)-1, l_fname, tm);
275         if (strcmp(new_filename, cur_filename))
276         {
277             strcpy(cur_filename, new_filename);
278             force = 1;
279         }
280     }
281
282     if (l_max_size > 0 && yaz_global_log_file && yaz_file_type == use_file)
283     {
284         long flen = ftell(yaz_global_log_file);
285         if (flen > l_max_size)
286         {
287             rotate_log(cur_filename);
288             force = 1;
289         }
290     }
291     if (force && yaz_file_type == use_file && *cur_filename)
292     {
293         yaz_log_close();
294         yaz_global_log_file = fopen(cur_filename, "a");
295         if (l_level < 0) l_level = default_log_level();
296         if (l_level & YLOG_FLUSH)
297             setvbuf(yaz_global_log_file, 0, _IONBF, 0);
298     }
299 }
300
301 void yaz_log_reopen()
302 {
303     time_t cur_time = time(0);
304 #if HAVE_LOCALTIME_R
305     struct tm tm0, *tm = &tm0;
306 #else
307     struct tm *tm;
308 #endif
309
310     nmem_mutex_enter(log_mutex);
311 #if HAVE_LOCALTIME_R
312     localtime_r(&cur_time, tm);
313 #else
314     tm = localtime(&cur_time);
315 #endif
316     yaz_log_open_check(tm, 1);
317     nmem_mutex_leave(log_mutex);
318 }
319
320 static void yaz_log_to_file(int level, FILE *file, const char *buf)
321 {
322     time_t ti = time(0);
323     int i;
324 #if HAVE_LOCALTIME_R
325     struct tm tm0, *tm = &tm0;
326 #else
327     struct tm *tm;
328 #endif
329
330     init_mutex();
331
332     nmem_mutex_enter(log_mutex);
333
334     #if HAVE_LOCALTIME_R
335     localtime_r(&ti, tm);
336 #else
337     tm = localtime(&ti);
338 #endif
339     
340     yaz_log_open_check(tm, 0);  
341     file = yaz_log_file(); /* file may change in yaz_log_open_check */
342
343     if (file)
344     {
345         char tbuf[TIMEFORMAT_LEN];
346         char flags[1024];
347         
348         *flags = '\0';
349         for (i = 0; level && mask_names[i].name; i++)
350             if ( mask_names[i].mask & level)
351             {
352                 if (*mask_names[i].name && mask_names[i].mask && 
353                     mask_names[i].mask != YLOG_ALL)
354                 {
355                     sprintf(flags + strlen(flags), "[%s]", mask_names[i].name);
356                     level &= ~mask_names[i].mask;
357                 }
358             }
359         
360         if (l_level & YLOG_NOTIME)
361             tbuf[0] = '\0';
362         else
363             strftime(tbuf, TIMEFORMAT_LEN-1, l_actual_format, tm);
364         tbuf[TIMEFORMAT_LEN-1] = '\0';
365         
366         fprintf(file, "%s %s%s %s%s\n", tbuf, l_prefix, flags, l_prefix2, buf);
367         if (l_level & (YLOG_FLUSH|YLOG_DEBUG) )
368             fflush(file);
369     }
370     nmem_mutex_leave(log_mutex);
371 }
372
373 void yaz_log(int level, const char *fmt, ...)
374 {
375     va_list ap;
376     char buf[4096];
377     FILE *file;
378     int o_level = level;
379
380     if (l_level < 0)
381         l_level = default_log_level();
382     if (!(level & l_level))
383         return;
384     va_start(ap, fmt);
385 #ifdef WIN32
386     _vsnprintf(buf, sizeof(buf)-1, fmt, ap);
387 #else
388 /* !WIN32 */
389 #if HAVE_VSNPRINTF
390     vsnprintf(buf, sizeof(buf), fmt, ap);
391 #else
392     vsprintf(buf, fmt, ap);
393 #endif
394 #endif
395 /* WIN32 */
396     if (o_level & YLOG_ERRNO)
397     {
398         strcat(buf, " [");
399         yaz_strerror(buf+strlen(buf), 2048);
400         strcat(buf, "]");
401     }
402     va_end (ap);
403     if (start_hook_func)
404         (*start_hook_func)(o_level, buf, start_hook_info);
405
406     file = yaz_log_file();
407     if (file)
408         yaz_log_to_file(level, file, buf);
409     if (end_hook_func)
410         (*end_hook_func)(o_level, buf, end_hook_info);
411 }
412
413 void yaz_log_time_format(const char *fmt)
414 {
415     if ( !fmt || !*fmt) 
416     { /* no format, default to new */
417         l_actual_format = l_new_default_format;
418         return; 
419     }
420     if (0==strcmp(fmt, "old"))
421     { /* force the old format */
422         l_actual_format = l_old_default_format;
423         return; 
424     }
425     /* else use custom format */
426     strncpy(l_custom_format, fmt, TIMEFORMAT_LEN-1);
427     l_custom_format[TIMEFORMAT_LEN-1] = '\0';
428     l_actual_format = l_custom_format;
429 }
430
431 /** cleans a loglevel name from leading paths and suffixes */
432 static char *clean_name(const char *name, int len, char *namebuf, int buflen)
433 {
434     char *p = namebuf;
435     char *start = namebuf;
436     if (buflen <= len)
437         len = buflen-1; 
438     strncpy(namebuf, name, len);
439     namebuf[len] = '\0';
440     while ((p = strchr(start, '/')))
441         start = p+1;
442     if ((p = strrchr(start, '.')))
443         *p = '\0';
444     return start;
445 }
446
447 static int define_module_bit(const char *name)
448 {
449     int i;
450     init_mutex();
451     nmem_mutex_enter(log_mutex);
452     for (i = 0; mask_names[i].name; i++)
453         if (0 == strcmp(mask_names[i].name, name))
454         {
455             nmem_mutex_leave(log_mutex);
456             return mask_names[i].mask;
457         }
458     if ( (i>=MAX_MASK_NAMES) || (next_log_bit >= 1<<31 ))
459     {
460         nmem_mutex_leave(log_mutex);
461         yaz_log(YLOG_WARN, "No more log bits left, not logging '%s'", name);
462         return 0;
463     }
464     mask_names[i].mask = next_log_bit;
465     next_log_bit = next_log_bit<<1;
466     mask_names[i].name = malloc(strlen(name)+1);
467     strcpy(mask_names[i].name, name);
468     mask_names[i+1].name = NULL;
469     mask_names[i+1].mask = 0;
470     nmem_mutex_leave(log_mutex);
471     return mask_names[i].mask;
472 }
473
474 int yaz_log_module_level(const char *name)
475 {
476     int i;
477     char clean[255];
478     char *n = clean_name(name, strlen(name), clean, sizeof(clean));
479     init_mutex();
480     
481     nmem_mutex_enter(log_mutex);
482     for (i = 0; mask_names[i].name; i++)
483         if (0==strcmp(n, mask_names[i].name))
484         {
485             nmem_mutex_leave(log_mutex);
486             yaz_log(YLOG_LOGLVL, "returning log bit 0x%x for '%s' %s",
487                     mask_names[i].mask, n, 
488                     strcmp(n,name) ? name : "");
489             return mask_names[i].mask;
490         }
491     nmem_mutex_leave(log_mutex);
492     yaz_log(YLOG_LOGLVL, "returning NO log bit for '%s' %s", n, 
493                     strcmp(n, name) ? name : "" );
494     return 0;
495 }
496
497 int yaz_log_mask_str(const char *str)
498 {
499     return yaz_log_mask_str_x(str, default_log_level());
500 }
501
502 int yaz_log_mask_str_x(const char *str, int level)
503 {
504     const char *p;
505
506     while (*str)
507     {
508         int negated = 0;
509         for (p = str; *p && *p != ','; p++)
510             ;
511         if (*str=='-')
512         {
513             negated = 1;
514             str++;
515         }
516         if (isdigit(*(unsigned char *) str))
517         {
518             level = atoi(str);
519         }
520         else 
521         {
522             char clean[509];
523             char *n = clean_name(str, p-str, clean, sizeof(clean));
524             int mask = define_module_bit(n);
525             if (!mask)
526                 level = 0;  /* 'none' clears them all */
527             else if (negated)
528                 level &= ~mask;
529             else
530                 level |= mask;
531         }
532         if (*p == ',')
533             p++;
534         str = p;
535     }
536     return level;
537 }
538 /*
539  * Local variables:
540  * c-basic-offset: 4
541  * indent-tabs-mode: nil
542  * End:
543  * vim: shiftwidth=4 tabstop=8 expandtab
544  */