source: MondoRescue/branches/stable/mondo/src/lib/mr_msg.c@ 1064

Last change on this file since 1064 was 1064, checked in by Bruno Cornec, 17 years ago

More controls at the compiler level
still working with the problems around variable arguments

  • Property svn:eol-style set to native
File size: 1.9 KB
Line 
1/*
2 * $Id$
3 *
4 * Code (c)2006 Bruno Cornec <bruno@mondorescue.org>
5 *
6 * Main file of mr_msg : a very small and simple
7 * library for messages management
8 *
9 * Provided under the GPLv2
10 */
11
12#ifndef _GNU_SOURCE
13#define _GNU_SOURCE
14#endif
15#include <stdio.h>
16#include <stdarg.h>
17#include <stdlib.h>
18
19static int mr_loglevel = 0;
20static char *mr_logfile = NULL;
21
22/* Cleanup function for messages */
23void mr_msg_close(void) {
24 free(mr_logfile);
25 mr_logfile = NULL;
26}
27
28/* Initialization function for messages */
29void mr_msg_init(const char *configfile, int loglevel) {
30 FILE *fout = NULL;
31 int res = 0;
32
33 asprintf(&mr_logfile,configfile);
34 if ((fout = fopen(mr_logfile, "w")) == NULL) {
35 fprintf(stderr,"Unable to write to %s\n",mr_logfile);
36 fprintf(stderr,"Logging desactivated\n");
37 mr_msg_close();
38 }
39 if ((res = fclose(fout)) != 0) {
40 fprintf(stderr,"Unable to close %s\n",mr_logfile);
41 }
42 mr_loglevel = loglevel;
43}
44
45/*
46 * Function that log a message. Not called directly
47 * but through other functions
48 */
49void _mr_msg(int debug, const char *file, const char *function, int line, const char *fmt, ...) {
50
51 int i = 0;
52 int res = 0;
53 FILE *fout = NULL;
54 va_list args;
55
56 if (mr_logfile == NULL) {
57 return;
58 }
59
60 if (debug <= mr_loglevel) {
61 if ((fout = fopen(mr_logfile, "a")) == NULL) {
62 fprintf(stderr,"Unable to append to %s\n",mr_logfile);
63 return;
64 }
65 va_start(args,fmt);
66
67 // add 2 spaces to distinguish log levels
68 if (debug > 0) {
69 for (i = 1; i < debug; i++)
70 fprintf(fout, " ");
71 fprintf(fout, "%s->%s#%d: ", file, function, line);
72 }
73 if (vfprintf(fout, fmt, args) < 0) {
74 fprintf(stderr,"Unable to print to %s\n",mr_logfile);
75 }
76
77 fprintf(fout, "\n");
78 if ((res = fclose(fout)) != 0) {
79 fprintf(stderr,"Unable to close %s\n",mr_logfile);
80 }
81 va_end(args);
82 }
83}
84
85void mr_msg(int level, const char *fmt, ...) {
86
87 va_list args;
88
89 va_start(args,fmt);
90 _mr_msg(level, __FILE__, __FUNCTION__, __LINE__, fmt, args);
91 va_end(args);
92}
Note: See TracBrowser for help on using the repository browser.