]> mj.ucw.cz Git - libucw.git/blob - lib/log.c
Don't log pid until log_fork() is called.
[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 char *log_progname;
17 static pid_t log_pid;
18
19 void
20 log_fork(void)
21 {
22   log_pid = getpid();
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 *prog = log_progname ?: "?";
31   char buf[32];
32
33   strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", tm);
34   fprintf(stderr, "%c %s ", cat, buf);
35   if (log_progname)
36     {
37       if (log_pid)
38         fprintf(stderr, "[%s (%d)] ", log_progname, log_pid);
39       else
40         fprintf(stderr, "[%s] ", log_progname);
41     }
42   else
43     {
44       if (log_pid)
45         fprintf(stderr, "[%d] ", log_pid);
46     }
47   vfprintf(stderr, msg, args);
48   fputc('\n', stderr);
49   fflush(stderr);
50 }
51
52 void
53 log(unsigned int cat, const char *msg, ...)
54 {
55   va_list args;
56
57   va_start(args, msg);
58   vlog(cat, msg, args);
59   va_end(args);
60 }
61
62 void
63 die(byte *msg, ...)
64 {
65   va_list args;
66
67   va_start(args, msg);
68   vlog(L_FATAL, msg, args);
69   va_end(args);
70   exit(1);
71 }
72
73 static byte *
74 basename(byte *n)
75 {
76   byte *p = n;
77
78   while (*n)
79         if (*n++ == '/')
80           p = n;
81   return p;
82 }
83
84 void
85 log_init(byte *argv0)
86 {
87   if (argv0)
88     log_progname = basename(argv0);
89 }
90
91 void
92 log_file(byte *name)
93 {
94   if (name)
95     {
96       int fd = open(name, O_WRONLY | O_CREAT | O_APPEND, 0666);
97       if (fd < 0)
98         die("Unable to open log file %s: %m", name);
99       close(2);
100       dup(fd);
101       close(fd);
102     }
103 }