Filename passed to yaz_log_init_file assumed to be in strftime format.
[yaz-moved-to-github.git] / src / log.c
1 /*
2  * Copyright (C) 1995-2005, Index Data ApS
3  * See the file LICENSE for details.
4  *
5  * $Id: log.c,v 1.28 2005-09-16 21:13:54 adam Exp $
6  */
7
8 /**
9  * \file log.c
10  * \brief Implements 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 #if HAS_STRERROR
46
47 #else
48 char *strerror(int n)
49 {
50     extern char *sys_errlist[];
51     return sys_errlist[n];
52 }
53
54 #endif
55
56 static int l_level = YLOG_DEFAULT_LEVEL;
57 static FILE *l_file = NULL;
58 static char l_prefix[512] = "";
59 static char l_prefix2[512] = "";
60 static char l_fname[512] = "";
61
62 static char l_old_default_format[] = "%H:%M:%S-%d/%m";
63 static char l_new_default_format[] = "%Y%m%d-%H%M%S";
64 #define TIMEFORMAT_LEN 50
65 static char l_custom_format[TIMEFORMAT_LEN] = "";
66 static char *l_actual_format = l_old_default_format;
67
68 /** l_max_size tells when to rotate the log. Default to 1 GB */
69 static const int l_def_max_size = 1024*1024*1024;
70 static int l_max_size = 1024*1024*1024;
71
72 #define MAX_MASK_NAMES 35   /* 32 bits plus a few combo names */
73 static struct {
74     int mask;
75     char *name;
76 } mask_names[MAX_MASK_NAMES] =
77 {
78     { YLOG_FATAL,  "fatal"},
79     { YLOG_DEBUG,  "debug"},
80     { YLOG_WARN,   "warn" },
81     { YLOG_LOG,    "log"  },
82     { YLOG_ERRNO,  ""},
83     { YLOG_MALLOC, "malloc"},
84     { YLOG_APP,    "app"  },
85     { YLOG_NOTIME, "notime" },
86     { YLOG_APP2,   "app2" }, 
87     { YLOG_APP3,   "app3" },
88     { YLOG_ALL,    "all"  },
89     { YLOG_FLUSH,  "flush" },
90     { YLOG_LOGLVL, "loglevel" }, 
91     { 0,           "none" },
92     { 0, NULL }
93     /* the rest will be filled in if the user defines dynamic modules*/
94 };  
95
96 static unsigned int next_log_bit = YLOG_LAST_BIT<<1; /* first dynamic bit */
97
98 static void init_mutex()
99 {
100     if (mutex_init_flag)
101         return;
102     nmem_mutex_create(&log_mutex);
103     mutex_init_flag = 1;
104 }
105
106 FILE *yaz_log_file(void)
107 {
108     if (!l_file)
109         l_file = stderr;
110     return l_file;
111 }
112
113 void yaz_log_init_file(const char *fname)
114 {
115     init_mutex();
116     if (fname)
117     {
118         strncpy(l_fname, fname, sizeof(l_fname)-1);
119         l_fname[sizeof(l_fname)-1] = '\0';
120     }
121     else
122         l_fname[0] = '\0';
123     yaz_log_reopen();
124 }
125
126 static void rotate_log(const char *cur_fname)
127 {
128     char newname[512];
129     strncpy(newname, cur_fname, 509);
130     newname[509] = '\0'; /* make sure it is terminated */
131     strcat(newname, ".1");
132 #ifdef WIN32
133     /* windows can't rename a file if it is open */
134     fclose(l_file);
135     l_file = 0;
136     MoveFileEx(cur_fname, newname, MOVEFILE_REPLACE_EXISTING);
137 #else
138     rename(cur_fname, newname);
139 #endif
140 }
141
142 void yaz_log_init_level(int level)
143 {
144     init_mutex();
145     if ( (l_level & YLOG_FLUSH) != (level & YLOG_FLUSH) )
146     {
147         l_level = level;
148         yaz_log_reopen(); /* make sure we set buffering right */
149     } else
150         l_level = level;
151     if (l_level  & YLOG_LOGLVL)
152     {  /* dump the log level bits */
153         const char *bittype = "Static ";
154         int i, sz;
155
156         yaz_log(YLOG_LOGLVL, "Setting log level to %d = 0x%08x",
157                 l_level, l_level);
158         /* determine size of mask_names (locked) */
159         nmem_mutex_enter(log_mutex);
160         for (sz = 0; mask_names[sz].name; sz++)
161             ;
162         nmem_mutex_leave(log_mutex);
163         /* second pass without lock */
164         for (i = 0; i < sz; i++)
165             if (mask_names[i].mask && *mask_names[i].name)
166                 if (strcmp(mask_names[i].name, "all") != 0)
167                 {
168                     yaz_log(YLOG_LOGLVL, "%s log bit %08x '%s' is %s",
169                             bittype, mask_names[i].mask, mask_names[i].name,
170                             (level & mask_names[i].mask)?  "ON": "off");
171                     if (mask_names[i].mask > YLOG_LAST_BIT)
172                         bittype = "Dynamic";
173                 }
174     }
175 }
176
177 void yaz_log_init_prefix(const char *prefix)
178 {
179     if (prefix && *prefix)
180         sprintf(l_prefix, "%.511s ", prefix);
181     else
182         *l_prefix = 0;
183 }
184
185 void yaz_log_init_prefix2(const char *prefix)
186 {
187     if (prefix && *prefix)
188         sprintf(l_prefix2, "%.511s ", prefix);
189     else
190         *l_prefix2 = 0;
191 }
192
193 void yaz_log_init(int level, const char *prefix, const char *fname)
194 {
195     init_mutex();
196     yaz_log_init_level(level);
197     yaz_log_init_prefix(prefix);
198     if (fname && *fname)
199         yaz_log_init_file(fname);
200 }
201
202 void yaz_log_init_max_size(int mx)
203 {
204     if (mx <0)
205         l_max_size = l_def_max_size;
206     else
207         l_max_size = mx;
208 }
209
210 static void (*start_hook_func)(int, const char *, void *) = NULL;
211 static void *start_hook_info;
212 static void (*end_hook_func)(int, const char *, void *) = NULL;
213 static void *end_hook_info;
214
215 void log_event_start(void (*func)(int, const char *, void *), void *info)
216 {
217     start_hook_func = func;
218     start_hook_info = info;
219 }
220
221 void log_event_end(void (*func)(int, const char *, void *), void *info)
222 {
223     end_hook_func = func;
224     end_hook_info = info;
225 }
226
227 static void yaz_log_open_check(int force)
228 {
229     char new_filename[512];
230     static char cur_filename[512] = "";
231     time_t new_time;
232     static time_t cur_time = 0;
233     struct tm tm;
234
235     nmem_mutex_enter(log_mutex);
236     if (!l_file)
237         l_file = stderr;
238
239     if (l_fname && *l_fname)
240     {
241         time(&new_time);
242         if (new_time != cur_time)
243         {
244             cur_time = new_time;
245             localtime_r(&new_time, &tm);
246             
247             strftime(new_filename, sizeof(new_filename)-1, l_fname, &tm);
248             if (strcmp(new_filename, cur_filename))
249             {
250                 strcpy(cur_filename, new_filename);
251                 force = 1;
252             }
253         }
254         if (l_max_size > 0 && (l_file && l_file != stderr))
255         {
256             long flen = ftell(l_file);
257             if (flen > l_max_size)
258             {
259                 rotate_log(cur_filename);
260                 force = 1;
261             }
262         }
263         if (force)
264         {
265             if (l_file && l_file != stderr)
266                 fclose(l_file);
267             l_file = fopen(cur_filename, "a");
268             if (l_level & YLOG_FLUSH)
269                 setvbuf(l_file, 0, _IONBF, 0);
270         }
271     }
272     nmem_mutex_leave(log_mutex);
273 }
274
275 void yaz_log_reopen()
276 {
277     yaz_log_open_check(1);
278 }
279
280 void yaz_log(int level, const char *fmt, ...)
281 {
282     va_list ap;
283     char buf[4096], flags[1024];
284     int i;
285     time_t ti;
286     struct tm *tim;
287     char tbuf[TIMEFORMAT_LEN] = "";
288     int o_level = level;
289
290     if (!(level & l_level))
291         return;
292     init_mutex();
293
294     yaz_log_open_check(0);
295
296     nmem_mutex_enter(log_mutex);
297     if (!l_file)
298         l_file = stderr;
299
300     *flags = '\0';
301     for (i = 0; level && mask_names[i].name; i++)
302         if ( mask_names[i].mask & level)
303         {
304             if (*mask_names[i].name && mask_names[i].mask && 
305                  mask_names[i].mask != YLOG_ALL)
306             {
307                 sprintf(flags + strlen(flags), "[%s]", mask_names[i].name);
308                 level &= ~mask_names[i].mask;
309             }
310         }
311
312     va_start(ap, fmt);
313 #ifdef WIN32
314     _vsnprintf(buf, sizeof(buf)-1, fmt, ap);
315 #else
316 /* !WIN32 */
317 #if HAVE_VSNPRINTF
318     vsnprintf(buf, sizeof(buf), fmt, ap);
319 #else
320     vsprintf(buf, fmt, ap);
321 #endif
322 #endif
323 /* WIN32 */
324     if (o_level & YLOG_ERRNO)
325     {
326         strcat(buf, " [");
327         yaz_strerror(buf+strlen(buf), 2048);
328         strcat(buf, "]");
329     }
330     va_end (ap);
331     if (start_hook_func)
332         (*start_hook_func)(o_level, buf, start_hook_info);
333     ti = time(0);
334     tim = localtime(&ti);
335     if (l_level & YLOG_NOTIME)
336         tbuf[0] = '\0';
337     else
338         strftime(tbuf, TIMEFORMAT_LEN-1, l_actual_format, tim);
339     tbuf[TIMEFORMAT_LEN-1] = '\0';
340     fprintf(l_file, "%s %s%s %s%s\n", tbuf, l_prefix, flags,
341             l_prefix2, buf);
342     if (l_level & (YLOG_FLUSH|YLOG_DEBUG) )
343         fflush(l_file);
344     if (end_hook_func)
345         (*end_hook_func)(o_level, buf, end_hook_info);
346     nmem_mutex_leave(log_mutex);
347 }
348
349 void yaz_log_time_format(const char *fmt)
350 {
351     if ( !fmt || !*fmt) 
352     { /* no format, default to new */
353         l_actual_format = l_new_default_format;
354         return; 
355     }
356     if (0==strcmp(fmt, "old"))
357     { /* force the old format */
358         l_actual_format = l_old_default_format;
359         return; 
360     }
361     /* else use custom format */
362     strncpy(l_custom_format, fmt, TIMEFORMAT_LEN-1);
363     l_custom_format[TIMEFORMAT_LEN-1] = '\0';
364     l_actual_format = l_custom_format;
365 }
366
367 /** cleans a loglevel name from leading paths and suffixes */
368 static char *clean_name(const char *name, int len, char *namebuf, int buflen)
369 {
370     char *p = namebuf;
371     char *start = namebuf;
372     if (buflen <= len)
373         len = buflen-1; 
374     strncpy(namebuf, name, len);
375     namebuf[len] = '\0';
376     while ((p = strchr(start, '/')))
377         start = p+1;
378     if ((p = strrchr(start, '.')))
379         *p = '\0';
380     return start;
381 }
382
383 static int define_module_bit(const char *name)
384 {
385     int i;
386     init_mutex();
387     nmem_mutex_enter(log_mutex);
388     for (i = 0; mask_names[i].name; i++)
389         if (0 == strcmp(mask_names[i].name, name))
390         {
391             nmem_mutex_leave(log_mutex);
392             return mask_names[i].mask;
393         }
394     if ( (i>=MAX_MASK_NAMES) || (next_log_bit >= 1<<31 ))
395     {
396         nmem_mutex_leave(log_mutex);
397         yaz_log(YLOG_WARN, "No more log bits left, not logging '%s'", name);
398         return 0;
399     }
400     mask_names[i].mask = next_log_bit;
401     next_log_bit = next_log_bit<<1;
402     mask_names[i].name = malloc(strlen(name)+1);
403     strcpy(mask_names[i].name, name);
404     mask_names[i+1].name = NULL;
405     mask_names[i+1].mask = 0;
406     nmem_mutex_leave(log_mutex);
407     return mask_names[i].mask;
408 }
409
410 int yaz_log_module_level(const char *name)
411 {
412     int i;
413     char clean[255];
414     char *n = clean_name(name, strlen(name), clean, sizeof(clean));
415     init_mutex();
416     
417     nmem_mutex_enter(log_mutex);
418     for (i = 0; mask_names[i].name; i++)
419         if (0==strcmp(n, mask_names[i].name))
420         {
421             nmem_mutex_leave(log_mutex);
422             yaz_log(YLOG_LOGLVL, "returning log bit 0x%x for '%s' %s",
423                     mask_names[i].mask, n, 
424                     strcmp(n,name) ? name : "");
425             return mask_names[i].mask;
426         }
427     nmem_mutex_leave(log_mutex);
428     yaz_log(YLOG_LOGLVL, "returning NO log bit for '%s' %s", n, 
429                     strcmp(n, name) ? name : "" );
430     return 0;
431 }
432
433 int yaz_log_mask_str(const char *str)
434 {
435     return yaz_log_mask_str_x(str, YLOG_DEFAULT_LEVEL);
436 }
437
438 int yaz_log_mask_str_x(const char *str, int level)
439 {
440     const char *p;
441
442     while (*str)
443     {
444         int negated = 0;
445         for (p = str; *p && *p != ','; p++)
446             ;
447         if (*str=='-')
448         {
449             negated = 1;
450             str++;
451         }
452         if (isdigit(*(unsigned char *) str))
453         {
454             level = atoi(str);
455         }
456         else 
457         {
458             char clean[509];
459             char *n = clean_name(str, p-str, clean, sizeof(clean));
460             int mask = define_module_bit(n);
461             if (!mask)
462                 level = 0;  /* 'none' clears them all */
463             else if (negated)
464                 level &= ~mask;
465             else
466                 level |= mask;
467         }
468         if (*p == ',')
469             p++;
470         str = p;
471     }
472     return level;
473 }
474 /*
475  * Local variables:
476  * c-basic-offset: 4
477  * indent-tabs-mode: nil
478  * End:
479  * vim: shiftwidth=4 tabstop=8 expandtab
480  */
481