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