1 /*
2  * Copyright 2008 Google Inc. All Rights Reserved.
3  *
4  * Author: md@google.com (Michael Davidson)
5  */
6 
7 #include <stdarg.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 
12 #include "logging.h"
13 
14 
15 static FILE		*log_fp		= NULL;
16 static const char	*program	= "";
17 static int		debug		= 0;
18 
19 
set_log_file(FILE * fp)20 void set_log_file(FILE *fp)
21 {
22 	log_fp = fp;
23 }
24 
set_program_name(const char * name)25 void set_program_name(const char *name)
26 {
27 	program = name;
28 }
29 
set_debug_level(int level)30 void set_debug_level(int level)
31 {
32 	debug = level;
33 }
34 
msg(enum msg_type msg_type,int data,const char * fmt,...)35 void msg(enum msg_type msg_type, int data, const char *fmt, ...)
36 {
37 	va_list		ap;
38 	int		err	= 0;
39 	const char	*type 	= NULL;
40 
41 	/*
42 	 * default is to log to stdout
43 	 */
44 	if (!log_fp)
45 		log_fp = stdout;
46 
47 	switch (msg_type) {
48 		case MSG_DEBUG:
49 			if (data > debug)
50 				return;
51 			type = "DEBUG";
52 			break;
53 		case MSG_INFO:
54 			type = "INFO";
55 			break;
56 		case MSG_WARN:
57 			type = "WARN";
58 			break;
59 		case MSG_ERROR:
60 			type = "ERROR";
61 			err = data;
62 			break;
63 		case MSG_FATAL:
64 			type = "FATAL";
65 			err = data;
66 			break;
67 	}
68 
69 	va_start(ap, fmt);
70 
71 	if (type)
72 		fprintf(log_fp, "%s: ", type);
73 
74 	if (program)
75 		fprintf(log_fp, "%s: ", program);
76 
77 	vfprintf(log_fp, fmt, ap);
78 
79 	if (err) {
80 		fprintf(log_fp, ": %s\n", strerror(err));
81 	} else {
82 		fputc('\n', log_fp);
83 	}
84 
85 	va_end(ap);
86 
87 	if (msg_type == MSG_FATAL)
88 		exit(EXIT_FAILURE);
89 }
90