]> mj.ucw.cz Git - libucw.git/blobdiff - lib/log.c
Make PROF_STR really work.
[libucw.git] / lib / log.c
index 16fe4e227f2ef574111953b836075df70fe858f7..eb3c0ab26d4736034b906fca3d5dacc445f61649 100644 (file)
--- a/lib/log.c
+++ b/lib/log.c
@@ -9,12 +9,14 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <stdarg.h>
+#include <string.h>
 #include <fcntl.h>
 #include <unistd.h>
 #include <time.h>
 
-static char *log_progname;
+static char *log_progname, log_name_patt[64], log_name[64];
 static pid_t log_pid;
+static int log_params;
 
 void
 log_fork(void)
@@ -22,6 +24,27 @@ log_fork(void)
   log_pid = getpid();
 }
 
+static void
+log_switch(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)
 {
@@ -29,6 +52,7 @@ vlog(unsigned int cat, const char *msg, va_list args)
   struct tm *tm = localtime(&tim);
   char buf[32];
 
+  log_switch(tm);
   strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", tm);
   fprintf(stderr, "%c %s ", cat, buf);
   if (log_progname)
@@ -70,7 +94,7 @@ die(byte *msg, ...)
 }
 
 static byte *
-basename(byte *n)
+log_basename(byte *n)
 {
   byte *p = n;
 
@@ -84,7 +108,7 @@ void
 log_init(byte *argv0)
 {
   if (argv0)
-    log_progname = basename(argv0);
+    log_progname = log_basename(argv0);
 }
 
 void
@@ -92,11 +116,11 @@ log_file(byte *name)
 {
   if (name)
     {
-      int 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);
+      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);
     }
 }