summaryrefslogtreecommitdiff
path: root/src/log.c
blob: 1c140be2e129e969e458e3bed3a645e332ba096c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include "log.h"
#include <stdio.h>
#include <stdarg.h>
#include <time.h>
#include <string.h>

static FILE *log_file = NULL;
static LogLevel min_log_level = LOG_INFO;

static const char *level_str(LogLevel level) {
    switch (level) {
        case LOG_DEBUG: return "DEBUG";
        case LOG_INFO:  return "INFO ";
        case LOG_WARN:  return "WARN ";
        case LOG_ERROR: return "ERROR";
        default:        return "?????";
    }
}

void log_init(const char *path, LogLevel min_level) {
    min_log_level = min_level;
    if (path) {
        log_file = fopen(path, "a");
        if (!log_file) {
            /* Fall back to stderr if we can't open the log file */
            fprintf(stderr, "umbrella: could not open log file %s, using stderr\n", path);
            log_file = stderr;
        }
    } else {
        log_file = stderr;
    }
}

void log_close(void) {
    if (log_file && log_file != stderr) {
        fclose(log_file);
        log_file = NULL;
    }
}

void log_write(LogLevel level, const char *fmt, ...) {
    if (level < min_log_level) return;
    if (!log_file) log_file = stderr;

    /* Timestamp */
    time_t now = time(NULL);
    struct tm *tm = localtime(&now);
    char ts[32];
    strftime(ts, sizeof(ts), "%Y-%m-%d %H:%M:%S", tm);

    fprintf(log_file, "[%s] [%s] ", ts, level_str(level));

    va_list args;
    va_start(args, fmt);
    vfprintf(log_file, fmt, args);
    va_end(args);

    fprintf(log_file, "\n");
    fflush(log_file);
}