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

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

More tests in
mr_msg function doesn't cascade to _mr_msg anymore, as it doesn't seem to work correctly with multiple varargs entries (I've not found how to do it correctly, so I give up for the moment)
lib code pass valgrind without issue.

  • Property svn:eol-style set to native
File size: 1.8 KB
RevLine 
[1054]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
[1064]12#ifndef _GNU_SOURCE
13#define _GNU_SOURCE
14#endif
[1054]15#include <stdio.h>
16#include <stdarg.h>
[1064]17#include <stdlib.h>
[1054]18
19static int mr_loglevel = 0;
20static char *mr_logfile = NULL;
21
[1065]22/*
23 * This function is in the lowest part of the tree
24 * It should not depend on any other function of the mr lib
25 */
26
[1054]27/* Cleanup function for messages */
28void mr_msg_close(void) {
29 free(mr_logfile);
30 mr_logfile = NULL;
[1065]31 mr_loglevel = 0;
[1054]32}
33
34/* Initialization function for messages */
35void mr_msg_init(const char *configfile, int loglevel) {
36 FILE *fout = NULL;
37 int res = 0;
38
39 asprintf(&mr_logfile,configfile);
40 if ((fout = fopen(mr_logfile, "w")) == NULL) {
41 fprintf(stderr,"Unable to write to %s\n",mr_logfile);
[1061]42 fprintf(stderr,"Logging desactivated\n");
[1054]43 mr_msg_close();
44 }
45 if ((res = fclose(fout)) != 0) {
46 fprintf(stderr,"Unable to close %s\n",mr_logfile);
47 }
48 mr_loglevel = loglevel;
49}
50
51/*
52 * Function that log a message. Not called directly
[1061]53 * but through other functions
[1054]54 */
[1065]55void mr_msg(int debug, const char *fmt, ...) {
[1054]56
57 int i = 0;
58 int res = 0;
59 FILE *fout = NULL;
[1064]60 va_list args;
[1054]61
62 if (mr_logfile == NULL) {
63 return;
64 }
65
66 if (debug <= mr_loglevel) {
67 if ((fout = fopen(mr_logfile, "a")) == NULL) {
68 fprintf(stderr,"Unable to append to %s\n",mr_logfile);
69 return;
70 }
71
72 // add 2 spaces to distinguish log levels
73 if (debug > 0) {
74 for (i = 1; i < debug; i++)
75 fprintf(fout, " ");
[1065]76 fprintf(fout, "%s->%s#%d: ", __FILE__, __FUNCTION__, __LINE__);
[1054]77 }
[1065]78 va_start(args,fmt);
[1054]79 if (vfprintf(fout, fmt, args) < 0) {
80 fprintf(stderr,"Unable to print to %s\n",mr_logfile);
81 }
[1065]82 va_end(args);
[1054]83
84 if ((res = fclose(fout)) != 0) {
85 fprintf(stderr,"Unable to close %s\n",mr_logfile);
86 }
87 }
88}
Note: See TracBrowser for help on using the repository browser.