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

Last change on this file since 1133 was 1133, checked in by bruno, 12 years ago

mr_msg used low level with a debug value of 1 (0 doesn't print enough info)
mr_file reviewed to also have low level debug functions

  • Property svn:eol-style set to native
File size: 2.0 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/*
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
27/* Cleanup function for messages */
28void mr_msg_close(void) {
29    free(mr_logfile);
30    mr_logfile = NULL;
31    mr_loglevel = 0;
32}
33
34/* Initialization function for messages */
35void mr_msg_init(const char *logfile, int loglevel) {
36    FILE *fout = NULL;
37    int res = 0;
38
39    asprintf(&mr_logfile,logfile);
40    if ((fout = fopen(mr_logfile, "w")) == NULL) {
41        fprintf(stderr,"Unable to write to %s\n",mr_logfile);
42        fprintf(stderr,"Logging desactivated\n");
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
53 * but through other functions
54 * fmt needs to be just before ...
55 * debug should be >0 to have file and line printed (real debug)
56 * If =0 it's an informative log message
57 */
58void mr_msg_int(int debug, int line, const char *file, const char *fmt, ...) {
59
60    int i = 0;
61    int res = 0;
62    FILE *fout = NULL;
63    va_list args;
64
65    if (mr_logfile == NULL) {
66        return;
67    }
68
69    if (debug <= mr_loglevel) {
70        if ((fout = fopen(mr_logfile, "a")) == NULL) {
71            fprintf(stderr,"Unable to append to %s\n",mr_logfile);
72            return;
73        }
74
75        // add 2 spaces to distinguish log levels
76        if (debug > 0) {
77            for (i = 1; i < debug; i++)
78                fprintf(fout, "  ");
79            fprintf(fout, "%s #%d: ", file, line);
80        }
81        va_start(args,fmt);
82        if (vfprintf(fout, fmt, args, "\n") < 0) {
83            fprintf(stderr,"Unable to print to %s\n",mr_logfile);
84        }
85        va_end(args);
86
87        if ((res = fclose(fout)) != 0) {
88            fprintf(stderr,"Unable to close %s\n",mr_logfile);
89        }
90    }
91}
Note: See TracBrowser for help on using the repository browser.