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