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