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