4 * Copyright (c) 2007 Nicholas Marriott <nicm@users.sourceforge.net>
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
15 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
16 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 #include <sys/types.h>
31 #define LOG_TYPE_OFF 0
32 #define LOG_TYPE_TTY 1
33 #define LOG_TYPE_FILE 2
34 int log_type
= LOG_TYPE_OFF
;
36 /* Log file, if needed. */
42 void log_vwrite(int, const char *, va_list);
43 __dead
void log_vfatal(const char *, va_list);
45 /* Open logging to tty. */
47 log_open_tty(int level
)
49 log_type
= LOG_TYPE_TTY
;
58 /* Open logging to file. */
60 log_open_file(int level
, const char *path
)
62 log_file
= fopen(path
, "w");
66 log_type
= LOG_TYPE_FILE
;
78 if (log_type
== LOG_TYPE_FILE
)
81 log_type
= LOG_TYPE_OFF
;
84 /* Write a log message. */
86 log_vwrite(int pri
, const char *msg
, va_list ap
)
99 if (asprintf(&fmt
, "%s\n", msg
) == -1)
101 if (vfprintf(f
, fmt
, ap
) == -1)
109 /* Log a warning with error string. */
111 log_warn(const char *msg
, ...)
117 if (asprintf(&fmt
, "%s: %s", msg
, strerror(errno
)) == -1)
119 log_vwrite(LOG_CRIT
, fmt
, ap
);
126 log_warnx(const char *msg
, ...)
131 log_vwrite(LOG_CRIT
, msg
, ap
);
135 /* Log an informational message. */
137 log_info(const char *msg
, ...)
141 if (log_level
> -1) {
143 log_vwrite(LOG_INFO
, msg
, ap
);
148 /* Log a debug message. */
150 log_debug(const char *msg
, ...)
156 log_vwrite(LOG_DEBUG
, msg
, ap
);
161 /* Log a debug message at level 2. */
163 log_debug2(const char *msg
, ...)
169 log_vwrite(LOG_DEBUG
, msg
, ap
);
174 /* Log a critical error, with error string if necessary, and die. */
176 log_vfatal(const char *msg
, va_list ap
)
181 if (asprintf(&fmt
, "fatal: %s: %s", msg
, strerror(errno
)) == -1)
183 log_vwrite(LOG_CRIT
, fmt
, ap
);
185 if (asprintf(&fmt
, "fatal: %s", msg
) == -1)
187 log_vwrite(LOG_CRIT
, fmt
, ap
);
194 /* Log a critical error, with error string, and die. */
195 __dead
void printflike1
196 log_fatal(const char *msg
, ...)
204 /* Log a critical error and die. */
205 __dead
void printflike1
206 log_fatalx(const char *msg
, ...)