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

#include <error.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <mach.h>

#include "ddekit/printf.h"

extern boolean_t using_std;
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 > 0)
		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 > 0) {
		ret = ddekit_print (tmp);
		free (tmp);
	}
	return ret;
}

int log_init ()
{
	if (using_std) {
		output = stdout;
	}
	else {
		char template[] = "/var/log/dde_log.XXXXXX";
		int ret = mkstemp (template);
		if (ret < 0) {
			error (0, errno, "mkstemp");
			return -1;
		}

		output = fopen (template, "a+");
		if (!output) {
			error (0, errno, "open %s", template);
			return -1;
		}
	}

	return 0;
}