#include <libintl.h>
#define _(str) gettext(str)
+#include <stdarg.h>
#include <stdio.h>
+#include <sys/time.h>
#include "log.h"
static FILE *file;
-static int log_level = LOG_DEBUG;
+int log_level = LOG_WARN;
-void log_open(const char *path, int lvl)
+void log_open(const char *path)
{
file = fopen(path, "a");
if (file)
- log_puts(LOG_INFO, "Start logging");
+ log_printf(LOG_INFO, "Start logging");
else
- fprintf(stderr, _("Cannot open log file: %s\n"), path);
+ log_printf(LOG_ERR, _("Cannot open log file: %s"), path);
}
-void log_puts(int lvl, const char *msg)
+void log_close()
{
- if (!file || lvl > log_level)
+ if (!file)
return ;
+ fclose(file);
+
+ file = NULL;
+}
+
+#define LOG_BUFFER 4096
+void log_printf(int lvl, const char *fmt, ...)
+{
+ struct timeval tv;
+ char buffer[1 + LOG_BUFFER];
+ va_list ap;
+ char *lvl_str;
+ FILE *stdf;
+
+ if (lvl > LOG_INFO && (!file || lvl > log_level))
+ return ;
+
+ va_start(ap, fmt);
+ vsnprintf(buffer, LOG_BUFFER, fmt, ap);
+ buffer[LOG_BUFFER] = '\0';
+ va_end(ap);
+
+ if (gettimeofday(&tv, NULL) != 0)
+ timerclear(&tv);
+
switch (lvl) {
case LOG_WARN:
- fputs("[WARN] ", file);
+ lvl_str = "[WARN]";
break;
case LOG_ERR:
- fputs("[ERR] ", file);
+ lvl_str = "[ERR]";
break;
case LOG_DEBUG:
- fputs("[DEBUG] ", file);
+ lvl_str = "[DEBUG]";
break;
case LOG_INFO:
- fputs("[INFO] ", file);
+ lvl_str = "[INFO]";
break;
default:
- fputs("[??] ", file);
+ lvl_str = "[??]";
}
- fputs(msg, file);
- fputc('\n', file);
-
- fflush(file);
-}
-
-void log_close()
-{
- if (!file)
- return ;
+ if (file && lvl <= log_level) {
+ fprintf(file, "[%ld] %s %s\n", tv.tv_sec, lvl_str, buffer);
+ fflush(file);
+ }
- fclose(file);
+ if (lvl <= LOG_INFO) {
+ if (lvl == LOG_WARN || lvl == LOG_ERR)
+ stdf = stderr;
+ else
+ stdf = stdout;
- file = NULL;
+ fprintf(stdf, "[%ld] %s %s\n", tv.tv_sec, lvl_str, buffer);
+ }
}
-