summaryrefslogtreecommitdiff
path: root/libddekit/printf.c
blob: bbd58863d4d2f5a57fd7cfbdeb438bba0a28034c (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
/*
 * \brief   Logging facility with printf()-like interface
 * \author  Thomas Friebel <yaron@yaron.de>
 * \date    2006-03-01
 */

#include <stdio.h>
#include <unistd.h>

#include "ddekit/printf.h"

static FILE *output;

/**
 * Log constant string message w/o arguments
 *
 * \param msg  message to be logged
 */
int ddekit_print(const char *msg)
{
	int ret;

	/* If LOG hasn't been initialized or failed its initialization,
	 * return the error. */
	if (output == NULL)
		return -1;

	ret = fprintf (output, "%s", msg);
	if (!ret)
		fflush (output);
	return ret;
}

/**
 * Log message with print()-like arguments
 *
 * \param fmt  format string followed by optional arguments
 */
int ddekit_printf(const char *fmt, ...)
{
	int res;
	va_list va;

	va_start(va, fmt);
	res = ddekit_vprintf(fmt, va);
	va_end(va);

	return res;
}

/* Log message with vprintf()-like arguments
 *
 * \param fmt  format string
 * \param va   variable argument list
 */
int ddekit_vprintf(const char *fmt, va_list va)
{
	char *tmp = NULL;
	int ret;

	ret = vasprintf (&tmp, fmt, va);
	if (!ret) {
		ret = ddekit_print (tmp);
		free (tmp);
	}
	return ret;
}

int log_init ()
{
	char *log_file_name = mktemp ("/tmp/dde_log.XXXXXX");
	output = fopen (log_file_name, "a+");
	if (!output) {
		error (0, errno, "open %s", log_file_name);
		return -1;
	}
	return 0;
}