]> mj.ucw.cz Git - libucw.git/blob - lib/log.c
Added __attribute__((format...)) to declaration of log(), so that
[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 <fcntl.h>
13 #include <unistd.h>
14 #include <sys/time.h>
15
16 static byte *log_progname;
17 static pid_t log_pid;
18
19 void
20 log_fork(void)
21 {
22   log_pid = 0;
23 }
24
25 static void
26 vlog(unsigned int cat, const char *msg, va_list args)
27 {
28   time_t tim = time(NULL);
29   struct tm *tm = localtime(&tim);
30   char buf[32];
31
32   if (!log_pid)
33     log_pid = getpid();
34   strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", tm);
35   fprintf(stderr, "%c %s ", cat, buf);
36   if (log_progname)
37     fprintf(stderr, "[%s (%d)] ", log_progname, log_pid);
38   vfprintf(stderr, msg, args);
39   fputc('\n', stderr);
40   fflush(stderr);
41 }
42
43 void
44 log(unsigned int cat, const char *msg, ...)
45 {
46   va_list args;
47
48   va_start(args, msg);
49   vlog(cat, msg, args);
50   va_end(args);
51 }
52
53 void
54 die(byte *msg, ...)
55 {
56   va_list args;
57
58   va_start(args, msg);
59   vlog(L_FATAL, msg, args);
60   va_end(args);
61   exit(1);
62 }
63
64 static byte *
65 basename(byte *n)
66 {
67   byte *p = n;
68
69   while (*n)
70         if (*n++ == '/')
71           p = n;
72   return p;
73 }
74
75 void
76 log_init(byte *argv0)
77 {
78   if (argv0)
79     log_progname = basename(argv0);
80 }
81
82 void
83 log_file(byte *name)
84 {
85   if (name)
86     {
87       int fd = open(name, O_WRONLY | O_CREAT | O_APPEND, 0666);
88       if (fd < 0)
89         die("Unable to open log file %s: %m", name);
90       close(2);
91       dup(fd);
92       close(fd);
93     }
94 }