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