]> mj.ucw.cz Git - libucw.git/blob - lib/log.c
78d5089f496cd20424dff62aef650e884dbd91d6
[libucw.git] / lib / log.c
1 /*
2  *      Sherlock Library -- Logging
3  *
4  *      (c) 1997 Martin Mares, <mj@atrey.karlin.mff.cuni.cz>
5  */
6
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <stdarg.h>
10 #include <fcntl.h>
11 #include <unistd.h>
12 #include <sys/time.h>
13
14 #include "lib.h"
15
16 static byte *progname = "???";
17 static pid_t pid;
18
19 static void
20 logit(int level, byte *msg, va_list args)
21 {
22   time_t tim;
23   struct tm *tm;
24   char buf[32];
25
26   tim = time(NULL);
27   tm = localtime(&tim);
28   strftime(buf, sizeof(buf), "%d-%m-%Y %H:%M:%S", tm);
29   fprintf(stderr, "%s %s [%d] <%d> ", buf, progname, pid, level);
30   vfprintf(stderr, msg, args);
31   fputc('\n', stderr);
32   fflush(stderr);
33 }
34
35 void
36 log(byte *msg, ...)
37 {
38   int level = 2;
39   va_list args;
40
41   va_start(args, msg);
42   if (msg[0] == '<' && msg[1] >= '0' && msg[1] <= '9' && msg[2] == '>')
43         {
44           level = msg[1] - '0';
45           msg += 3;
46         }
47   logit(level, msg, args);
48   va_end(args);
49 }
50
51 void
52 die(byte *msg, ...)
53 {
54   va_list args;
55
56   va_start(args, msg);
57   logit(9, msg, args);
58   va_end(args);
59   exit(99);
60 }
61
62 static byte *
63 basename(byte *n)
64 {
65   byte *p = n;
66
67   while (*n)
68         if (*n++ == '/')
69           p = n;
70   return p;
71 }
72
73 void
74 initlog(byte *argv0)
75 {
76   if (argv0)
77     progname = basename(argv0);
78   pid = getpid();
79 }
80
81 void
82 open_log_file(byte *name)
83 {
84   if (name)
85     {
86       int fd = open(name, O_WRONLY | O_CREAT | O_APPEND, 0666);
87       if (fd < 0)
88         die("Unable to open log file");
89       close(2);
90       dup(fd);
91       close(fd);
92     }
93 }