summaryrefslogtreecommitdiff
path: root/lib/log.c
blob: c45f73538412604bfb632502c4835a8089b348fb (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
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>

#include "log.h"

/* Message buffer */
#define MBUF_SIZE 512

static void (*log_output)(int level, const char *source, int line, const char *msg) = NULL;
static int min_level = LOGL_INFO;

void
dp_log_set_output(void (*output)(int, const char *, int, const char *))
{
	log_output = output;
}

void
dp_log_set_level(int level)
{
	min_level = level;
}

void
dp_log_write(int level, const char *source, int line, const char *fmt, ...)
{
	char mbuf[MBUF_SIZE];
	char *msg;
	va_list va;
	int len;

	if (level < min_level)
		return;
	if (!log_output)
		return;

	msg = mbuf;
	va_start(va, fmt);
	len = vsnprintf(msg, MBUF_SIZE, fmt, va);
	va_end(va);

	if (len >= MBUF_SIZE)
	{
		msg = (char *)malloc(len + 1);
		va_start(va, fmt);
		len = vsnprintf(msg, len + 1, fmt, va);
		va_end(va);
	}

	log_output(level, source, line, msg);

	if (msg != mbuf)
		free(msg);
}