Add lock/unlock for YAZ log writes YAZ-843
[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 void yaz_log_lock(void)
109 {
110     yaz_mutex_enter(log_mutex);
111 }
112
113 void yaz_log_unlock(void)
114 {
115     yaz_mutex_leave(log_mutex);
116 }
117
118 void yaz_log_init_globals(void)
119 {
120     char *env;
121
122     if (log_mutex == 0)
123         yaz_mutex_create(&log_mutex);
124 #if YAZ_POSIX_THREADS
125     pthread_atfork(yaz_log_lock, yaz_log_unlock, yaz_log_unlock);
126 #endif
127     env = getenv("YAZ_LOG");
128     if (env)
129         l_level = yaz_log_mask_str_x(env, l_level);
130 }
131
132 FILE *yaz_log_file(void)
133 {
134     FILE *f = 0;
135     switch (yaz_log_info.type)
136     {
137         case use_stderr: f = stderr; break;
138         case use_none: f = 0; break;
139         case use_file: f = yaz_log_info.log_file; break;
140     }
141     return f;
142 }
143
144 void yaz_log_close(void)
145 {
146     if (yaz_log_info.type == use_file && yaz_log_info.log_file)
147     {
148         fclose(yaz_log_info.log_file);
149         yaz_log_info.log_file = 0;
150     }
151 }
152
153 void yaz_log_init_file(const char *fname)
154 {
155     yaz_init_globals();
156
157     yaz_log_close();
158     if (fname)
159     {
160         if (*fname == '\0')
161             yaz_log_info.type = use_stderr; /* empty name; use stderr */
162         else
163             yaz_log_info.type = use_file;
164         strncpy(yaz_log_info.l_fname, fname, sizeof(yaz_log_info.l_fname)-1);
165         yaz_log_info.l_fname[sizeof(yaz_log_info.l_fname)-1] = '\0';
166     }
167     else
168     {
169         yaz_log_info.type = use_none;  /* NULL name; use no file at all */
170         yaz_log_info.l_fname[0] = '\0';
171     }
172     yaz_log_reopen();
173 }
174
175 static void rotate_log(const char *cur_fname)
176 {
177     int i;
178
179 #ifdef WIN32
180     /* windows can't rename a file if it is open */
181     yaz_log_close();
182 #endif
183     for (i = 0; i<9; i++)
184     {
185         char fname_str[FILENAME_MAX];
186         struct stat stat_buf;
187
188         yaz_snprintf(fname_str, sizeof(fname_str), "%s.%d", cur_fname, i);
189         if (stat(fname_str, &stat_buf) != 0)
190             break;
191     }
192     for (; i >= 0; --i)
193     {
194         char fname_str[2][FILENAME_MAX];
195
196         if (i > 0)
197             yaz_snprintf(fname_str[0], sizeof(fname_str[0]),
198                          "%s.%d", cur_fname, i-1);
199         else
200             yaz_snprintf(fname_str[0], sizeof(fname_str[0]),
201                          "%s", cur_fname);
202         yaz_snprintf(fname_str[1], sizeof(fname_str[1]),
203                      "%s.%d", cur_fname, i);
204 #ifdef WIN32
205         MoveFileEx(fname_str[0], fname_str[1], MOVEFILE_REPLACE_EXISTING);
206 #else
207         rename(fname_str[0], fname_str[1]);
208 #endif
209     }
210 }
211
212
213 void yaz_log_init_level(int level)
214 {
215     yaz_init_globals();
216     if ( (l_level & YLOG_FLUSH) != (level & YLOG_FLUSH) )
217     {
218         l_level = level;
219         yaz_log_reopen(); /* make sure we set buffering right */
220     }
221     else
222         l_level = level;
223
224     if (l_level  & YLOG_LOGLVL)
225     {  /* dump the log level bits */
226         const char *bittype = "Static ";
227         int i, sz;
228
229         yaz_log(YLOG_LOGLVL, "Setting log level to %d = 0x%08x",
230                 l_level, l_level);
231         /* determine size of mask_names (locked) */
232         for (sz = 0; mask_names[sz].name; sz++)
233             ;
234         /* second pass without lock */
235         for (i = 0; i < sz; i++)
236             if (mask_names[i].mask && *mask_names[i].name)
237                 if (strcmp(mask_names[i].name, "all") != 0)
238                 {
239                     yaz_log(YLOG_LOGLVL, "%s log bit %08x '%s' is %s",
240                             bittype, mask_names[i].mask, mask_names[i].name,
241                             (level & mask_names[i].mask)?  "ON": "off");
242                     if (mask_names[i].mask > YLOG_LAST_BIT)
243                         bittype = "Dynamic";
244                 }
245     }
246 }
247
248 void yaz_log_init_prefix(const char *prefix)
249 {
250     if (prefix && *prefix)
251         yaz_snprintf(yaz_log_info.l_prefix,
252                      sizeof(yaz_log_info.l_prefix), "%s ", prefix);
253     else
254         *yaz_log_info.l_prefix = 0;
255 }
256
257 void yaz_log_init_prefix2(const char *prefix)
258 {
259     if (prefix && *prefix)
260         yaz_snprintf(yaz_log_info.l_prefix2,
261                      sizeof(yaz_log_info.l_prefix2), "%s ", prefix);
262     else
263         *yaz_log_info.l_prefix2 = 0;
264 }
265
266 void yaz_log_init(int level, const char *prefix, const char *fname)
267 {
268     yaz_init_globals();
269     yaz_log_init_level(level);
270     yaz_log_init_prefix(prefix);
271     if (fname && *fname)
272         yaz_log_init_file(fname);
273 }
274
275 void yaz_log_init_max_size(int mx)
276 {
277     if (mx > 0)
278         l_max_size = mx;
279     else
280         l_max_size = 0;
281 }
282
283 void yaz_log_set_handler(void (*func)(int, const char *, void *), void *info)
284 {
285     hook_func = func;
286     hook_info = info;
287 }
288
289 void log_event_start(void (*func)(int, const char *, void *), void *info)
290 {
291     start_hook_func = func;
292     start_hook_info = info;
293 }
294
295 void log_event_end(void (*func)(int, const char *, void *), void *info)
296 {
297     end_hook_func = func;
298     end_hook_info = info;
299 }
300
301 static void yaz_log_open_check(struct tm *tm, int force, const char *filemode)
302 {
303     char new_filename[512];
304     static char cur_filename[512] = "";
305
306     if (yaz_log_info.type != use_file)
307         return;
308
309     if (*yaz_log_info.l_fname)
310     {
311         strftime(new_filename, sizeof(new_filename)-1, yaz_log_info.l_fname,
312                  tm);
313         if (strcmp(new_filename, cur_filename))
314         {
315             strcpy(cur_filename, new_filename);
316             force = 1;
317         }
318     }
319
320     if (l_max_size > 0 && yaz_log_info.log_file)
321     {
322         long flen = ftell(yaz_log_info.log_file);
323         if (flen > l_max_size)
324         {
325             rotate_log(cur_filename);
326             force = 1;
327         }
328     }
329     if (force && *cur_filename)
330     {
331         FILE *new_file;
332 #ifdef WIN32
333         yaz_log_close();
334 #endif
335         if (!strncmp(cur_filename, "fd=", 3))
336             new_file = fdopen(atoi(cur_filename + 3), filemode);
337         else
338             new_file = fopen(cur_filename, filemode);
339         if (new_file)
340         {
341             yaz_log_close();
342             yaz_log_info.log_file = new_file;
343         }
344         else
345         {
346             /* disable log rotate */
347             l_max_size = 0;
348         }
349     }
350 }
351
352 static void yaz_log_do_reopen(const char *filemode)
353 {
354     time_t cur_time = time(0);
355 #if HAVE_LOCALTIME_R
356     struct tm tm0, *tm = &tm0;
357 #else
358     struct tm *tm;
359 #endif
360
361     yaz_log_lock();
362 #if HAVE_LOCALTIME_R
363     localtime_r(&cur_time, tm);
364 #else
365     tm = localtime(&cur_time);
366 #endif
367     yaz_log_open_check(tm, 1, filemode);
368     yaz_log_unlock();
369 }
370
371
372 void yaz_log_reopen()
373 {
374     yaz_log_do_reopen("a");
375 }
376
377 void yaz_log_trunc()
378 {
379     yaz_log_do_reopen("w");
380 }
381
382 static void yaz_strftime(char *dst, size_t sz,
383                          const char *fmt, const struct tm *tm)
384 {
385     strftime(dst, sz, fmt, tm);
386 }
387
388 static void yaz_log_to_file(int level, const char *fmt, va_list ap,
389                             const char *error_cp)
390 {
391     FILE *file;
392     time_t ti = time(0);
393 #if HAVE_LOCALTIME_R
394     struct tm tm0, *tm = &tm0;
395 #else
396     struct tm *tm;
397 #endif
398
399     yaz_log_lock();
400 #if HAVE_LOCALTIME_R
401     localtime_r(&ti, tm);
402 #else
403     tm = localtime(&ti);
404 #endif
405
406     yaz_log_open_check(tm, 0, "a");
407     file = yaz_log_file(); /* file may change in yaz_log_open_check */
408
409     if (file)
410     {
411         char tbuf[TIMEFORMAT_LEN];
412         char tid[TID_LEN];
413         char flags[1024];
414         int i;
415
416         *flags = '\0';
417         for (i = 0; level && mask_names[i].name; i++)
418             if ( mask_names[i].mask & level)
419             {
420                 if (*mask_names[i].name && mask_names[i].mask &&
421                     mask_names[i].mask != YLOG_ALL)
422                 {
423                     if (strlen(flags) + strlen(mask_names[i].name)
424                                              <   sizeof(flags) - 4)
425                     {
426                         strcat(flags, "[");
427                         strcat(flags, mask_names[i].name);
428                         strcat(flags, "]");
429                     }
430                     level &= ~mask_names[i].mask;
431                 }
432             }
433
434         tbuf[0] = '\0';
435         if (!(l_level & YLOG_NOTIME))
436         {
437             yaz_strftime(tbuf, TIMEFORMAT_LEN-2, l_actual_format, tm);
438             tbuf[TIMEFORMAT_LEN-2] = '\0';
439         }
440         if (tbuf[0])
441             strcat(tbuf, " ");
442         tid[0] = '\0';
443
444         if (l_level & YLOG_TID)
445         {
446             yaz_thread_id_cstr(tid, sizeof(tid)-1);
447             if (tid[0])
448                 strcat(tid, " ");
449         }
450
451         fprintf(file, "%s%s%s%s %s", tbuf, yaz_log_info.l_prefix,
452                 tid, flags, yaz_log_info.l_prefix2);
453         vfprintf(file, fmt, ap);
454         if (error_cp)
455             fprintf(file, " [%s]", error_cp);
456         fputs("\n", file);
457         if (l_level & YLOG_FLUSH)
458             fflush(file);
459     }
460     yaz_log_unlock();
461 }
462
463 void yaz_log(int level, const char *fmt, ...)
464 {
465     va_list ap;
466     FILE *file;
467     int o_level = level;
468     char *error_cp = 0, error_buf[128];
469
470     if (o_level & YLOG_ERRNO)
471     {
472         yaz_strerror(error_buf, sizeof(error_buf));
473         error_cp = error_buf;
474     }
475     yaz_init_globals();
476     if (!(level & l_level))
477         return;
478     va_start(ap, fmt);
479
480     file = yaz_log_file();
481     if (start_hook_func || hook_func || end_hook_func)
482     {
483         char buf[1024];
484         /* 30 is enough for our 'rest of output' message */
485         yaz_vsnprintf(buf, sizeof(buf)-30, fmt, ap);
486         if (strlen(buf) >= sizeof(buf)-31)
487             strcat(buf, " [rest of output omitted]");
488         if (start_hook_func)
489             (*start_hook_func)(o_level, buf, start_hook_info);
490         if (hook_func)
491             (*hook_func)(o_level, buf, hook_info);
492         if (file)
493             yaz_log_to_file(level, fmt, ap, error_cp);
494         if (end_hook_func)
495             (*end_hook_func)(o_level, buf, end_hook_info);
496     }
497     else
498     {
499         if (file)
500             yaz_log_to_file(level, fmt, ap, error_cp);
501     }
502     va_end(ap);
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     yaz_init_globals();
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     yaz_init_globals(); /* since l_level may be affected */
585     return yaz_log_mask_str_x(str, l_level);
586 }
587
588 /* this function is called by yaz_log_init_globals & yaz_init_globals
589    and, thus, may not call any of them indirectly */
590 int yaz_log_mask_str_x(const char *str, int level)
591 {
592     const char *p;
593
594     while (*str)
595     {
596         int negated = 0;
597         for (p = str; *p && *p != ','; p++)
598             ;
599         if (*str=='-')
600         {
601             negated = 1;
602             str++;
603         }
604         if (yaz_isdigit(*str))
605         {
606             level = atoi(str);
607         }
608         else
609         {
610             char clean[509];
611             char *n = clean_name(str, (size_t) (p - str), clean, sizeof(clean));
612             int mask = define_module_bit(n);
613             if (!mask)
614                 level = 0;  /* 'none' clears them all */
615             else if (negated)
616                 level &= ~mask;
617             else
618                 level |= mask;
619         }
620         if (*p == ',')
621             p++;
622         str = p;
623     }
624     return level;
625 }
626 /*
627  * Local variables:
628  * c-basic-offset: 4
629  * c-file-style: "Stroustrup"
630  * indent-tabs-mode: nil
631  * End:
632  * vim: shiftwidth=4 tabstop=8 expandtab
633  */
634