X-Git-Url: http://mj.ucw.cz/gitweb/?a=blobdiff_plain;f=lib%2Flog.c;h=eb3c0ab26d4736034b906fca3d5dacc445f61649;hb=c982330d65a5ff8930682b250612ea135db2d4f6;hp=55431cc1fb06e2985fcb90d2ceebb544c4d06ab6;hpb=b65c2563a8a425593f91dfcb82ede8cf53fec6cd;p=libucw.git diff --git a/lib/log.c b/lib/log.c index 55431cc1..eb3c0ab2 100644 --- a/lib/log.c +++ b/lib/log.c @@ -1,49 +1,84 @@ /* * Sherlock Library -- Logging * - * (c) 1997 Martin Mares, + * (c) 1997--2001 Martin Mares */ +#include "lib/lib.h" + #include #include #include +#include +#include #include -#include +#include -#include "lib.h" +static char *log_progname, log_name_patt[64], log_name[64]; +static pid_t log_pid; +static int log_params; -static byte *progname = "???"; -static pid_t pid; +void +log_fork(void) +{ + log_pid = getpid(); +} static void -logit(int level, byte *msg, va_list args) +log_switch(struct tm *tm) { - time_t tim; - struct tm *tm; + int fd; + char name[64]; + + if (!log_name_patt[0] || + log_name[0] && !log_params) + return; + strftime(name, sizeof(name), log_name_patt, tm); + if (!strcmp(name, log_name)) + return; + strcpy(log_name, name); + fd = open(name, O_WRONLY | O_CREAT | O_APPEND, 0666); + if (fd < 0) + die("Unable to open log file %s: %m", name); + close(2); + dup(fd); + close(fd); +} + +static void +vlog(unsigned int cat, const char *msg, va_list args) +{ + time_t tim = time(NULL); + struct tm *tm = localtime(&tim); char buf[32]; - tim = time(NULL); - tm = localtime(&tim); - strftime(buf, sizeof(buf), "%d-%m-%y %H:%M:%S", tm); - fprintf(stderr, "%s %s [%d] <%d> ", buf, progname, pid, level); + log_switch(tm); + strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", tm); + fprintf(stderr, "%c %s ", cat, buf); + if (log_progname) + { + if (log_pid) + fprintf(stderr, "[%s (%d)] ", log_progname, log_pid); + else + fprintf(stderr, "[%s] ", log_progname); + } + else + { + if (log_pid) + fprintf(stderr, "[%d] ", log_pid); + } vfprintf(stderr, msg, args); fputc('\n', stderr); fflush(stderr); } void -log(byte *msg, ...) +log(unsigned int cat, const char *msg, ...) { - int level = 2; va_list args; va_start(args, msg); - if (msg[0] == '<' && msg[1] >= '0' && msg[1] <= '9' && msg[2] == '>') - { - level = msg[1] - '0'; - msg += 3; - } - logit(level, msg, args); + vlog(cat, msg, args); va_end(args); } @@ -53,13 +88,13 @@ die(byte *msg, ...) va_list args; va_start(args, msg); - logit(9, msg, args); + vlog(L_FATAL, msg, args); va_end(args); - exit(99); + exit(1); } static byte * -basename(byte *n) +log_basename(byte *n) { byte *p = n; @@ -70,8 +105,22 @@ basename(byte *n) } void -initlog(byte *argv0) +log_init(byte *argv0) +{ + if (argv0) + log_progname = log_basename(argv0); +} + +void +log_file(byte *name) { - progname = basename(argv0); - pid = getpid(); + if (name) + { + time_t tim = time(NULL); + struct tm *tm = localtime(&tim); + strcpy(log_name_patt, name); + log_params = !!strchr(name, '%'); + log_name[0] = 0; + log_switch(tm); + } }