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