summaryrefslogtreecommitdiff
path: root/log.c
blob: e0c77e5f1f2d8ea1c2d998cdbae50c2d20a3b548 (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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include "log.h"
#include "macros.h"
#include "misc.h"

typedef enum colour colour;

enum colour {
	BLACK,
	RED,
	GREEN,
	YELLOW,
	BLUE,
	MAGENTA,
	CYAN,
	WHITE,
	NUM_COLOURS,
	RESET = NUM_COLOURS,
};

static const char *print_ansi_colour(colour colour, int is_bg, int is_bright) {
	if (colour < NUM_COLOURS) {
		static char str[const_strlen("\x1B[100m")+1] = {0};
		int colour_code = colour + 30;

		if (is_bg) {
			colour_code += 10;
		}

		if (is_bright) {
			colour_code += 60;
		}

		snprintf(str, sizeof(str)-1, "\x1B[%dm", colour_code);
		return str;
	} else {
		return "\x1B[0m";
	}
}

static const char *print_priority_colour(int priority) {
	colour colour = RESET;
	int is_bg = 0;
	int is_bright = 0;

	switch (priority) {
		case LOG_ERR	: colour = RED; break;
		case LOG_WARNING: colour = YELLOW; is_bright = 1; break;
		case LOG_NOTICE	: colour = CYAN; break;
		case LOG_INFO	: colour = MAGENTA; break;
		case LOG_DEBUG	: colour = GREEN; break;
		default		: break;
	}

	return print_ansi_colour(colour, is_bg, is_bright);
}

static const char *priority_to_str(int priority) {
	switch (priority) {
		case LOG_ERR	: return "ERROR";
		case LOG_WARNING: return "WARNING";
		case LOG_NOTICE	: return "NOTICE";
		case LOG_INFO	: return "INFO";
		case LOG_DEBUG	: return "DEBUG";
		default		: return "UNKNOWN";
	}
}

void vprintlog(log_output output_type, int priority, const char *fmt, va_list args) {
	const char *priority_str = priority_to_str(priority);
	char *buf = calloc(vformat_len_copy(fmt, args)+1, sizeof(char));
	vsprintf(buf, fmt, args);

	switch (output_type) {
		case LOG_OUT_SYSLOG: {
			syslog(priority, "%s: %s", priority_str, buf);
			break;
		}
		case LOG_OUT_STDERR:
		case LOG_OUT_STDOUT: {
			FILE *output = (output_type == LOG_OUT_STDOUT) ? stdout : stderr;
			fprintf(output, "%s%s: %s\x1B[0m\n", print_priority_colour(priority), priority_str, buf);
			break;
		}
		default:
			break;
	}
	free(buf);
}

void printlog(log_output output_type, int priority, const char *fmt, ...) {
	va_list args;
	va_start(args, fmt);
	vprintlog(output_type, priority, fmt, args);
	va_end(args);
}