YAZ_LOG environment variable.
[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.30 2006-03-13 17:33:19 mike 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 #if HAS_STRERROR
46
47 #else
48 char *strerror(int n)
49 {
50     extern char *sys_errlist[];
51     return sys_errlist[n];
52 }
53
54 #endif
55
56
57 static int default_log_level() {
58     char *env = getenv("YAZ_LOG");
59     if (env != 0)
60         return yaz_log_mask_str_x(env, YLOG_DEFAULT_LEVEL);
61     else
62         return YLOG_DEFAULT_LEVEL;
63 }
64
65
66 static int l_level = -1;        /* will be set from default_log_level() */
67 static FILE *l_file = NULL;
68 static char l_prefix[512] = "";
69 static char l_prefix2[512] = "";
70 static char l_fname[512] = "";
71
72 static char l_old_default_format[] = "%H:%M:%S-%d/%m";
73 static char l_new_default_format[] = "%Y%m%d-%H%M%S";
74 #define TIMEFORMAT_LEN 50
75 static char l_custom_format[TIMEFORMAT_LEN] = "";
76 static char *l_actual_format = l_old_default_format;
77
78 /** l_max_size tells when to rotate the log. Default to 1 GB */
79 static const int l_def_max_size = 1024*1024*1024;
80 static int l_max_size = 1024*1024*1024;
81
82 #define MAX_MASK_NAMES 35   /* 32 bits plus a few combo names */
83 static struct {
84     int mask;
85     char *name;
86 } mask_names[MAX_MASK_NAMES] =
87 {
88     { YLOG_FATAL,  "fatal"},
89     { YLOG_DEBUG,  "debug"},
90     { YLOG_WARN,   "warn" },
91     { YLOG_LOG,    "log"  },
92     { YLOG_ERRNO,  ""},
93     { YLOG_MALLOC, "malloc"},
94     { YLOG_APP,    "app"  },
95     { YLOG_NOTIME, "notime" },
96     { YLOG_APP2,   "app2" }, 
97     { YLOG_APP3,   "app3" },
98     { YLOG_ALL,    "all"  },
99     { YLOG_FLUSH,  "flush" },
100     { YLOG_LOGLVL, "loglevel" }, 
101     { 0,           "none" },
102     { 0, NULL }
103     /* the rest will be filled in if the user defines dynamic modules*/
104 };  
105
106 static unsigned int next_log_bit = YLOG_LAST_BIT<<1; /* first dynamic bit */
107
108 static void init_mutex()
109 {
110     if (mutex_init_flag)
111         return;
112     nmem_mutex_create(&log_mutex);
113     mutex_init_flag = 1;
114 }
115
116 FILE *yaz_log_file(void)
117 {
118     if (!l_file)
119         l_file = stderr;
120     return l_file;
121 }
122
123 void yaz_log_init_file(const char *fname)
124 {
125     init_mutex();
126     if (fname)
127     {
128         strncpy(l_fname, fname, sizeof(l_fname)-1);
129         l_fname[sizeof(l_fname)-1] = '\0';
130     }
131     else
132         l_fname[0] = '\0';
133     yaz_log_reopen();
134 }
135
136 static void rotate_log(const char *cur_fname)
137 {
138     char newname[512];
139     strncpy(newname, cur_fname, 509);
140     newname[509] = '\0'; /* make sure it is terminated */
141     strcat(newname, ".1");
142 #ifdef WIN32
143     /* windows can't rename a file if it is open */
144     fclose(l_file);
145     l_file = 0;
146     MoveFileEx(cur_fname, newname, MOVEFILE_REPLACE_EXISTING);
147 #else
148     rename(cur_fname, newname);
149 #endif
150 }
151
152 void yaz_log_init_level(int level)
153 {
154     init_mutex();
155     if (l_level < 0) l_level = default_log_level();
156     if ( (l_level & YLOG_FLUSH) != (level & YLOG_FLUSH) )
157     {
158         l_level = level;
159         yaz_log_reopen(); /* make sure we set buffering right */
160     } else
161         l_level = level;
162     if (l_level  & YLOG_LOGLVL)
163     {  /* dump the log level bits */
164         const char *bittype = "Static ";
165         int i, sz;
166
167         yaz_log(YLOG_LOGLVL, "Setting log level to %d = 0x%08x",
168                 l_level, l_level);
169         /* determine size of mask_names (locked) */
170         nmem_mutex_enter(log_mutex);
171         for (sz = 0; mask_names[sz].name; sz++)
172             ;
173         nmem_mutex_leave(log_mutex);
174         /* second pass without lock */
175         for (i = 0; i < sz; i++)
176             if (mask_names[i].mask && *mask_names[i].name)
177                 if (strcmp(mask_names[i].name, "all") != 0)
178                 {
179                     yaz_log(YLOG_LOGLVL, "%s log bit %08x '%s' is %s",
180                             bittype, mask_names[i].mask, mask_names[i].name,
181                             (level & mask_names[i].mask)?  "ON": "off");
182                     if (mask_names[i].mask > YLOG_LAST_BIT)
183                         bittype = "Dynamic";
184                 }
185     }
186 }
187
188 void yaz_log_init_prefix(const char *prefix)
189 {
190     if (prefix && *prefix)
191         sprintf(l_prefix, "%.511s ", prefix);
192     else
193         *l_prefix = 0;
194 }
195
196 void yaz_log_init_prefix2(const char *prefix)
197 {
198     if (prefix && *prefix)
199         sprintf(l_prefix2, "%.511s ", prefix);
200     else
201         *l_prefix2 = 0;
202 }
203
204 void yaz_log_init(int level, const char *prefix, const char *fname)
205 {
206     init_mutex();
207     yaz_log_init_level(level);
208     yaz_log_init_prefix(prefix);
209     if (fname && *fname)
210         yaz_log_init_file(fname);
211 }
212
213 void yaz_log_init_max_size(int mx)
214 {
215     if (mx <0)
216         l_max_size = l_def_max_size;
217     else
218         l_max_size = mx;
219 }
220
221 static void (*start_hook_func)(int, const char *, void *) = NULL;
222 static void *start_hook_info;
223 static void (*end_hook_func)(int, const char *, void *) = NULL;
224 static void *end_hook_info;
225
226 void log_event_start(void (*func)(int, const char *, void *), void *info)
227 {
228     start_hook_func = func;
229     start_hook_info = info;
230 }
231
232 void log_event_end(void (*func)(int, const char *, void *), void *info)
233 {
234     end_hook_func = func;
235     end_hook_info = info;
236 }
237
238 static void yaz_log_open_check(struct tm *tm, int force)
239 {
240     char new_filename[512];
241     static char cur_filename[512] = "";
242
243     if (!l_file)
244         l_file = stderr;
245
246     if (l_fname && *l_fname)
247     {
248         strftime(new_filename, sizeof(new_filename)-1, l_fname, tm);
249         if (strcmp(new_filename, cur_filename))
250         {
251             strcpy(cur_filename, new_filename);
252             force = 1;
253         }
254         if (l_max_size > 0 && (l_file && l_file != stderr))
255         {
256             long flen = ftell(l_file);
257             if (flen > l_max_size)
258             {
259                 rotate_log(cur_filename);
260                 force = 1;
261             }
262         }
263         if (force)
264         {
265             if (l_file && l_file != stderr)
266                 fclose(l_file);
267             l_file = fopen(cur_filename, "a");
268             if (l_level < 0) l_level = default_log_level();
269             if (l_level & YLOG_FLUSH)
270                 setvbuf(l_file, 0, _IONBF, 0);
271         }
272     }
273 }
274
275 void yaz_log_reopen()
276 {
277     time_t cur_time = time(0);
278 #if HAVE_LOCALTIME_R
279     struct tm tm0, *tm = &tm0;
280 #else
281     struct tm *tm;
282 #endif
283
284     nmem_mutex_enter(log_mutex);
285 #if HAVE_LOCALTIME_R
286     localtime_r(&cur_time, tm);
287 #else
288     tm = localtime(&cur_time);
289 #endif
290     yaz_log_open_check(tm, 1);
291     nmem_mutex_leave(log_mutex);
292 }
293
294 void yaz_log(int level, const char *fmt, ...)
295 {
296     va_list ap;
297     char buf[4096], flags[1024];
298     int i;
299     time_t ti;
300 #if HAVE_LOCALTIME_R
301     struct tm tm0, *tm = &tm0;
302 #else
303     struct tm *tm;
304 #endif
305     char tbuf[TIMEFORMAT_LEN] = "";
306     int o_level = level;
307
308     if (l_level < 0) l_level = default_log_level();
309     if (!(level & l_level))
310         return;
311     init_mutex();
312
313     nmem_mutex_enter(log_mutex);
314     ti = time(0);
315 #if HAVE_LOCALTIME_R
316     localtime_r(&ti, tm);
317 #else
318     tm = localtime(&ti);
319 #endif
320
321     yaz_log_open_check(tm, 0);
322
323     if (!l_file)
324         l_file = stderr;
325
326     *flags = '\0';
327     for (i = 0; level && mask_names[i].name; i++)
328         if ( mask_names[i].mask & level)
329         {
330             if (*mask_names[i].name && mask_names[i].mask && 
331                  mask_names[i].mask != YLOG_ALL)
332             {
333                 sprintf(flags + strlen(flags), "[%s]", mask_names[i].name);
334                 level &= ~mask_names[i].mask;
335             }
336         }
337
338     va_start(ap, fmt);
339 #ifdef WIN32
340     _vsnprintf(buf, sizeof(buf)-1, fmt, ap);
341 #else
342 /* !WIN32 */
343 #if HAVE_VSNPRINTF
344     vsnprintf(buf, sizeof(buf), fmt, ap);
345 #else
346     vsprintf(buf, fmt, ap);
347 #endif
348 #endif
349 /* WIN32 */
350     if (o_level & YLOG_ERRNO)
351     {
352         strcat(buf, " [");
353         yaz_strerror(buf+strlen(buf), 2048);
354         strcat(buf, "]");
355     }
356     va_end (ap);
357     if (start_hook_func)
358         (*start_hook_func)(o_level, buf, start_hook_info);
359     if (l_level & YLOG_NOTIME)
360         tbuf[0] = '\0';
361     else
362         strftime(tbuf, TIMEFORMAT_LEN-1, l_actual_format, tm);
363     tbuf[TIMEFORMAT_LEN-1] = '\0';
364     fprintf(l_file, "%s %s%s %s%s\n", tbuf, l_prefix, flags,
365             l_prefix2, buf);
366     if (l_level & (YLOG_FLUSH|YLOG_DEBUG) )
367         fflush(l_file);
368     if (end_hook_func)
369         (*end_hook_func)(o_level, buf, end_hook_info);
370     nmem_mutex_leave(log_mutex);
371 }
372
373 void yaz_log_time_format(const char *fmt)
374 {
375     if ( !fmt || !*fmt) 
376     { /* no format, default to new */
377         l_actual_format = l_new_default_format;
378         return; 
379     }
380     if (0==strcmp(fmt, "old"))
381     { /* force the old format */
382         l_actual_format = l_old_default_format;
383         return; 
384     }
385     /* else use custom format */
386     strncpy(l_custom_format, fmt, TIMEFORMAT_LEN-1);
387     l_custom_format[TIMEFORMAT_LEN-1] = '\0';
388     l_actual_format = l_custom_format;
389 }
390
391 /** cleans a loglevel name from leading paths and suffixes */
392 static char *clean_name(const char *name, int len, char *namebuf, int buflen)
393 {
394     char *p = namebuf;
395     char *start = namebuf;
396     if (buflen <= len)
397         len = buflen-1; 
398     strncpy(namebuf, name, len);
399     namebuf[len] = '\0';
400     while ((p = strchr(start, '/')))
401         start = p+1;
402     if ((p = strrchr(start, '.')))
403         *p = '\0';
404     return start;
405 }
406
407 static int define_module_bit(const char *name)
408 {
409     int i;
410     init_mutex();
411     nmem_mutex_enter(log_mutex);
412     for (i = 0; mask_names[i].name; i++)
413         if (0 == strcmp(mask_names[i].name, name))
414         {
415             nmem_mutex_leave(log_mutex);
416             return mask_names[i].mask;
417         }
418     if ( (i>=MAX_MASK_NAMES) || (next_log_bit >= 1<<31 ))
419     {
420         nmem_mutex_leave(log_mutex);
421         yaz_log(YLOG_WARN, "No more log bits left, not logging '%s'", name);
422         return 0;
423     }
424     mask_names[i].mask = next_log_bit;
425     next_log_bit = next_log_bit<<1;
426     mask_names[i].name = malloc(strlen(name)+1);
427     strcpy(mask_names[i].name, name);
428     mask_names[i+1].name = NULL;
429     mask_names[i+1].mask = 0;
430     nmem_mutex_leave(log_mutex);
431     return mask_names[i].mask;
432 }
433
434 int yaz_log_module_level(const char *name)
435 {
436     int i;
437     char clean[255];
438     char *n = clean_name(name, strlen(name), clean, sizeof(clean));
439     init_mutex();
440     
441     nmem_mutex_enter(log_mutex);
442     for (i = 0; mask_names[i].name; i++)
443         if (0==strcmp(n, mask_names[i].name))
444         {
445             nmem_mutex_leave(log_mutex);
446             yaz_log(YLOG_LOGLVL, "returning log bit 0x%x for '%s' %s",
447                     mask_names[i].mask, n, 
448                     strcmp(n,name) ? name : "");
449             return mask_names[i].mask;
450         }
451     nmem_mutex_leave(log_mutex);
452     yaz_log(YLOG_LOGLVL, "returning NO log bit for '%s' %s", n, 
453                     strcmp(n, name) ? name : "" );
454     return 0;
455 }
456
457 int yaz_log_mask_str(const char *str)
458 {
459     return yaz_log_mask_str_x(str, default_log_level());
460 }
461
462 int yaz_log_mask_str_x(const char *str, int level)
463 {
464     const char *p;
465
466     while (*str)
467     {
468         int negated = 0;
469         for (p = str; *p && *p != ','; p++)
470             ;
471         if (*str=='-')
472         {
473             negated = 1;
474             str++;
475         }
476         if (isdigit(*(unsigned char *) str))
477         {
478             level = atoi(str);
479         }
480         else 
481         {
482             char clean[509];
483             char *n = clean_name(str, p-str, clean, sizeof(clean));
484             int mask = define_module_bit(n);
485             if (!mask)
486                 level = 0;  /* 'none' clears them all */
487             else if (negated)
488                 level &= ~mask;
489             else
490                 level |= mask;
491         }
492         if (*p == ',')
493             p++;
494         str = p;
495     }
496     return level;
497 }
498 /*
499  * Local variables:
500  * c-basic-offset: 4
501  * indent-tabs-mode: nil
502  * End:
503  * vim: shiftwidth=4 tabstop=8 expandtab
504  */