Added yaz_log_trunc() to truncate the log file
[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.37 2006-07-06 13:10:31 heikki 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
191 void yaz_log_init_level(int level)
192 {
193     init_mutex();
194     if (l_level < 0) l_level = default_log_level();
195     if ( (l_level & YLOG_FLUSH) != (level & YLOG_FLUSH) )
196     {
197         l_level = level;
198         yaz_log_reopen(); /* make sure we set buffering right */
199     } else
200         l_level = level;
201     if (l_level  & YLOG_LOGLVL)
202     {  /* dump the log level bits */
203         const char *bittype = "Static ";
204         int i, sz;
205
206         yaz_log(YLOG_LOGLVL, "Setting log level to %d = 0x%08x",
207                 l_level, l_level);
208         /* determine size of mask_names (locked) */
209         nmem_mutex_enter(log_mutex);
210         for (sz = 0; mask_names[sz].name; sz++)
211             ;
212         nmem_mutex_leave(log_mutex);
213         /* second pass without lock */
214         for (i = 0; i < sz; i++)
215             if (mask_names[i].mask && *mask_names[i].name)
216                 if (strcmp(mask_names[i].name, "all") != 0)
217                 {
218                     yaz_log(YLOG_LOGLVL, "%s log bit %08x '%s' is %s",
219                             bittype, mask_names[i].mask, mask_names[i].name,
220                             (level & mask_names[i].mask)?  "ON": "off");
221                     if (mask_names[i].mask > YLOG_LAST_BIT)
222                         bittype = "Dynamic";
223                 }
224     }
225 }
226
227 void yaz_log_init_prefix(const char *prefix)
228 {
229     if (prefix && *prefix)
230         sprintf(l_prefix, "%.511s ", prefix);
231     else
232         *l_prefix = 0;
233 }
234
235 void yaz_log_init_prefix2(const char *prefix)
236 {
237     if (prefix && *prefix)
238         sprintf(l_prefix2, "%.511s ", prefix);
239     else
240         *l_prefix2 = 0;
241 }
242
243 void yaz_log_init(int level, const char *prefix, const char *fname)
244 {
245     init_mutex();
246     yaz_log_init_level(level);
247     yaz_log_init_prefix(prefix);
248     if (fname && *fname)
249         yaz_log_init_file(fname);
250 }
251
252 void yaz_log_init_max_size(int mx)
253 {
254     if (mx <0)
255         l_max_size = l_def_max_size;
256     else
257         l_max_size = mx;
258 }
259
260 void yaz_log_set_handler(void (*func)(int, const char *, void *), void *info)
261 {
262     hook_func = func;
263     hook_info = info;
264 }
265
266 void log_event_start(void (*func)(int, const char *, void *), void *info)
267 {
268      start_hook_func = func;
269      start_hook_info = info;
270 }
271
272 void log_event_end(void (*func)(int, const char *, void *), void *info)
273 {
274      end_hook_func = func;
275      end_hook_info = info;
276 }
277
278 static void yaz_log_open_check(struct tm *tm, int force, const char *filemode)
279 {
280     char new_filename[512];
281     static char cur_filename[512] = "";
282
283     if (l_fname && *l_fname)
284     {
285         strftime(new_filename, sizeof(new_filename)-1, l_fname, tm);
286         if (strcmp(new_filename, cur_filename))
287         {
288             strcpy(cur_filename, new_filename);
289             force = 1;
290         }
291     }
292
293     if (l_max_size > 0 && yaz_global_log_file && yaz_file_type == use_file)
294     {
295         long flen = ftell(yaz_global_log_file);
296         if (flen > l_max_size)
297         {
298             rotate_log(cur_filename);
299             force = 1;
300         }
301     }
302     if (force && yaz_file_type == use_file && *cur_filename)
303     {
304         yaz_log_close();
305         yaz_global_log_file = fopen(cur_filename, filemode);
306         if (l_level < 0) l_level = default_log_level();
307         if (l_level & YLOG_FLUSH)
308             setvbuf(yaz_global_log_file, 0, _IONBF, 0);
309     }
310 }
311
312 static void yaz_log_do_reopen(const char *filemode)
313 {
314     time_t cur_time = time(0);
315 #if HAVE_LOCALTIME_R
316     struct tm tm0, *tm = &tm0;
317 #else
318     struct tm *tm;
319 #endif
320
321     nmem_mutex_enter(log_mutex);
322 #if HAVE_LOCALTIME_R
323     localtime_r(&cur_time, tm);
324 #else
325     tm = localtime(&cur_time);
326 #endif
327     yaz_log_open_check(tm, 1, filemode );
328     nmem_mutex_leave(log_mutex);
329 }
330
331
332 void yaz_log_reopen()
333 {
334     yaz_log_do_reopen("a");
335 }
336
337 void yaz_log_trunc()
338 {
339     yaz_log_do_reopen("w");
340 }
341
342
343
344 static void yaz_strftime(char *dst, size_t sz,
345                          const char *fmt, const struct tm *tm)
346 {
347     const char *cp = strstr(fmt, "%!");
348     if (cp && strlen(fmt) < 60)
349     {
350         char fmt2[80];
351         char tpidstr[20];
352 #ifdef WIN32
353         DWORD tid = GetCurrentThreadId();
354 #else
355         long tid = 0;
356 #if YAZ_POSIX_THREADS
357         tid = pthread_self();
358 #endif
359 #endif
360         memcpy(fmt2, fmt, cp-fmt);
361         fmt2[cp-fmt] = '\0';
362         sprintf(tpidstr, "%08lx", (long) tid);
363         strcat(fmt2, tpidstr);
364         strcat(fmt2, cp+2);
365         strftime(dst, sz, fmt2, tm);     
366     }
367     else
368         strftime(dst, sz, fmt, tm);
369 }
370                             
371 static void yaz_log_to_file(int level, FILE *file, const char *buf)
372 {
373     time_t ti = time(0);
374     int i;
375 #if HAVE_LOCALTIME_R
376     struct tm tm0, *tm = &tm0;
377 #else
378     struct tm *tm;
379 #endif
380
381     init_mutex();
382
383     nmem_mutex_enter(log_mutex);
384
385     #if HAVE_LOCALTIME_R
386     localtime_r(&ti, tm);
387 #else
388     tm = localtime(&ti);
389 #endif
390     
391     yaz_log_open_check(tm, 0, "a");  
392     file = yaz_log_file(); /* file may change in yaz_log_open_check */
393
394     if (file)
395     {
396         char tbuf[TIMEFORMAT_LEN];
397         char flags[1024];
398         
399         *flags = '\0';
400         for (i = 0; level && mask_names[i].name; i++)
401             if ( mask_names[i].mask & level)
402             {
403                 if (*mask_names[i].name && mask_names[i].mask && 
404                     mask_names[i].mask != YLOG_ALL)
405                 {
406                     sprintf(flags + strlen(flags), "[%s]", mask_names[i].name);
407                     level &= ~mask_names[i].mask;
408                 }
409             }
410         
411         if (l_level & YLOG_NOTIME)
412             tbuf[0] = '\0';
413         else
414             yaz_strftime(tbuf, TIMEFORMAT_LEN-1, l_actual_format, tm);
415         tbuf[TIMEFORMAT_LEN-1] = '\0';
416         
417         fprintf(file, "%s %s%s %s%s\n", tbuf, l_prefix, flags, l_prefix2, buf);
418         if (l_level & (YLOG_FLUSH|YLOG_DEBUG) )
419             fflush(file);
420     }
421     nmem_mutex_leave(log_mutex);
422 }
423
424 void yaz_log(int level, const char *fmt, ...)
425 {
426     va_list ap;
427     char buf[4096];
428     FILE *file;
429     int o_level = level;
430
431     if (l_level < 0)
432         l_level = default_log_level();
433     if (!(level & l_level))
434         return;
435     va_start(ap, fmt);
436 #ifdef WIN32
437     _vsnprintf(buf, sizeof(buf)-1, fmt, ap);
438 #else
439 /* !WIN32 */
440 #if HAVE_VSNPRINTF
441     vsnprintf(buf, sizeof(buf), fmt, ap);
442 #else
443     vsprintf(buf, fmt, ap);
444 #endif
445 #endif
446 /* WIN32 */
447     if (o_level & YLOG_ERRNO)
448     {
449         strcat(buf, " [");
450         yaz_strerror(buf+strlen(buf), 2048);
451         strcat(buf, "]");
452     }
453     va_end (ap);
454     if (start_hook_func)
455         (*start_hook_func)(o_level, buf, start_hook_info);
456     if (hook_func)
457         (*hook_func)(o_level, buf, hook_info);
458     file = yaz_log_file();
459     if (file)
460         yaz_log_to_file(level, file, buf);
461     if (end_hook_func)
462         (*end_hook_func)(o_level, buf, end_hook_info);
463 }
464
465 void yaz_log_time_format(const char *fmt)
466 {
467     if ( !fmt || !*fmt) 
468     { /* no format, default to new */
469         l_actual_format = l_new_default_format;
470         return; 
471     }
472     if (0==strcmp(fmt, "old"))
473     { /* force the old format */
474         l_actual_format = l_old_default_format;
475         return; 
476     }
477     /* else use custom format */
478     strncpy(l_custom_format, fmt, TIMEFORMAT_LEN-1);
479     l_custom_format[TIMEFORMAT_LEN-1] = '\0';
480     l_actual_format = l_custom_format;
481 }
482
483 /** cleans a loglevel name from leading paths and suffixes */
484 static char *clean_name(const char *name, int len, char *namebuf, int buflen)
485 {
486     char *p = namebuf;
487     char *start = namebuf;
488     if (buflen <= len)
489         len = buflen-1; 
490     strncpy(namebuf, name, len);
491     namebuf[len] = '\0';
492     while ((p = strchr(start, '/')))
493         start = p+1;
494     if ((p = strrchr(start, '.')))
495         *p = '\0';
496     return start;
497 }
498
499 static int define_module_bit(const char *name)
500 {
501     int i;
502     init_mutex();
503     nmem_mutex_enter(log_mutex);
504     for (i = 0; mask_names[i].name; i++)
505         if (0 == strcmp(mask_names[i].name, name))
506         {
507             nmem_mutex_leave(log_mutex);
508             return mask_names[i].mask;
509         }
510     if ( (i>=MAX_MASK_NAMES) || (next_log_bit >= 1<<31 ))
511     {
512         nmem_mutex_leave(log_mutex);
513         yaz_log(YLOG_WARN, "No more log bits left, not logging '%s'", name);
514         return 0;
515     }
516     mask_names[i].mask = next_log_bit;
517     next_log_bit = next_log_bit<<1;
518     mask_names[i].name = malloc(strlen(name)+1);
519     strcpy(mask_names[i].name, name);
520     mask_names[i+1].name = NULL;
521     mask_names[i+1].mask = 0;
522     nmem_mutex_leave(log_mutex);
523     return mask_names[i].mask;
524 }
525
526 int yaz_log_module_level(const char *name)
527 {
528     int i;
529     char clean[255];
530     char *n = clean_name(name, strlen(name), clean, sizeof(clean));
531     init_mutex();
532     
533     nmem_mutex_enter(log_mutex);
534     for (i = 0; mask_names[i].name; i++)
535         if (0==strcmp(n, mask_names[i].name))
536         {
537             nmem_mutex_leave(log_mutex);
538             yaz_log(YLOG_LOGLVL, "returning log bit 0x%x for '%s' %s",
539                     mask_names[i].mask, n, 
540                     strcmp(n,name) ? name : "");
541             return mask_names[i].mask;
542         }
543     nmem_mutex_leave(log_mutex);
544     yaz_log(YLOG_LOGLVL, "returning NO log bit for '%s' %s", n, 
545                     strcmp(n, name) ? name : "" );
546     return 0;
547 }
548
549 int yaz_log_mask_str(const char *str)
550 {
551     return yaz_log_mask_str_x(str, default_log_level());
552 }
553
554 int yaz_log_mask_str_x(const char *str, int level)
555 {
556     const char *p;
557
558     while (*str)
559     {
560         int negated = 0;
561         for (p = str; *p && *p != ','; p++)
562             ;
563         if (*str=='-')
564         {
565             negated = 1;
566             str++;
567         }
568         if (isdigit(*(unsigned char *) str))
569         {
570             level = atoi(str);
571         }
572         else 
573         {
574             char clean[509];
575             char *n = clean_name(str, p-str, clean, sizeof(clean));
576             int mask = define_module_bit(n);
577             if (!mask)
578                 level = 0;  /* 'none' clears them all */
579             else if (negated)
580                 level &= ~mask;
581             else
582                 level |= mask;
583         }
584         if (*p == ',')
585             p++;
586         str = p;
587     }
588     return level;
589 }
590 /*
591  * Local variables:
592  * c-basic-offset: 4
593  * indent-tabs-mode: nil
594  * End:
595  * vim: shiftwidth=4 tabstop=8 expandtab
596  */