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