tizen 2.0
[external/module-init-tools.git] / logging.c
1 #define _GNU_SOURCE /* asprintf */
2
3 #include <stdlib.h>
4 #include <stdarg.h>
5 #include <stdio.h>
6 #include <syslog.h>
7
8 #include "logging.h"
9
10 /* Do we use syslog for messages or stderr? */
11 int logging = 0;
12
13 /* Do we want to silently drop all warnings? */
14 int quiet = 0;
15
16 /* Do we want informative messages as well as errors? */
17 int verbose = 0;
18
19 void message(const char *prefix, const char *fmt, va_list *arglist)
20 {
21         int ret;
22         char *buf, *buf2;
23
24         ret = vasprintf(&buf, fmt, *arglist);
25         if (ret >= 0)
26                 ret = asprintf(&buf2, "%s%s", prefix, buf);
27
28         if (ret < 0)
29                 buf2 = "FATAL: Out of memory.\n";
30
31         if (logging)
32                 syslog(LOG_NOTICE, "%s", buf2);
33         else
34                 fprintf(stderr, "%s", buf2);
35
36         if (ret < 0)
37                 exit(1);
38
39         free(buf2);
40         free(buf);
41 }
42
43 void warn(const char *fmt, ...)
44 {
45         va_list arglist;
46         va_start(arglist, fmt);
47         if (!quiet)
48                 message("WARNING: ", fmt, &arglist);
49         va_end(arglist);
50 }
51
52 void error(const char *fmt, ...)
53 {
54         va_list arglist;
55         va_start(arglist, fmt);
56         message("ERROR: ", fmt, &arglist);
57         va_end(arglist);
58 }
59
60 void fatal(const char *fmt, ...)
61 {
62         va_list arglist;
63         va_start(arglist, fmt);
64         message("FATAL: ", fmt, &arglist);
65         va_end(arglist);
66         exit(1);
67 }
68
69 /* If we don't flush, then child processes print before we do */
70 void info(const char *fmt, ...)
71 {
72         va_list arglist;
73         va_start(arglist, fmt);
74         if (verbose) {
75                 vfprintf(stdout, fmt, arglist);
76                 fflush(stdout);
77         }
78         va_end(arglist);
79 }