]> mj.ucw.cz Git - libucw.git/blob - lib/log.c
e25476b673362b58721857a8783e0e8358b13b2d
[libucw.git] / lib / log.c
1 /*
2  *      Sherlock Library -- Logging
3  *
4  *      (c) 1997--2001 Martin Mares <mj@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #include "lib/lib.h"
11
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <stdarg.h>
15 #include <string.h>
16 #include <fcntl.h>
17 #include <unistd.h>
18 #include <time.h>
19
20 static char *log_progname, log_name_patt[64], log_name[64];
21 static pid_t log_pid;
22 static int log_params;
23
24 void
25 log_fork(void)
26 {
27   log_pid = getpid();
28 }
29
30 static void
31 log_switch(struct tm *tm)
32 {
33   int fd;
34   char name[64];
35
36   if (!log_name_patt[0] ||
37       log_name[0] && !log_params)
38     return;
39   strftime(name, sizeof(name), log_name_patt, tm);
40   if (!strcmp(name, log_name))
41     return;
42   strcpy(log_name, name);
43   fd = open(name, O_WRONLY | O_CREAT | O_APPEND, 0666);
44   if (fd < 0)
45     die("Unable to open log file %s: %m", name);
46   close(2);
47   dup(fd);
48   close(fd);
49 }
50
51 static void
52 vlog(unsigned int cat, const char *msg, va_list args)
53 {
54   time_t tim = time(NULL);
55   struct tm *tm = localtime(&tim);
56   char buf[32];
57
58   log_switch(tm);
59   strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", tm);
60   fprintf(stderr, "%c %s ", cat, buf);
61   if (log_progname)
62     {
63       if (log_pid)
64         fprintf(stderr, "[%s (%d)] ", log_progname, log_pid);
65       else
66         fprintf(stderr, "[%s] ", log_progname);
67     }
68   else
69     {
70       if (log_pid)
71         fprintf(stderr, "[%d] ", log_pid);
72     }
73   vfprintf(stderr, msg, args);
74   fputc('\n', stderr);
75   fflush(stderr);
76 }
77
78 void
79 log(unsigned int cat, const char *msg, ...)
80 {
81   va_list args;
82
83   va_start(args, msg);
84   vlog(cat, msg, args);
85   va_end(args);
86 }
87
88 void
89 die(byte *msg, ...)
90 {
91   va_list args;
92
93   va_start(args, msg);
94   vlog(L_FATAL, msg, args);
95   va_end(args);
96   exit(1);
97 }
98
99 void
100 assert_failed(char *assertion, char *file, int line)
101 {
102   log(L_FATAL, "Assertion `%s' failed at %s:%d", assertion, file, line);
103   abort();
104 }
105
106 static byte *
107 log_basename(byte *n)
108 {
109   byte *p = n;
110
111   while (*n)
112         if (*n++ == '/')
113           p = n;
114   return p;
115 }
116
117 void
118 log_init(byte *argv0)
119 {
120   if (argv0)
121     log_progname = log_basename(argv0);
122 }
123
124 void
125 log_file(byte *name)
126 {
127   if (name)
128     {
129       time_t tim = time(NULL);
130       struct tm *tm = localtime(&tim);
131       strcpy(log_name_patt, name);
132       log_params = !!strchr(name, '%');
133       log_name[0] = 0;
134       log_switch(tm);
135     }
136 }