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