/* * $Id$ * * Code (c)2006 Bruno Cornec * * Main file of mr_msg : a very small and simple * library for messages management * * Provided under the GPLv2 */ #include #include static int mr_loglevel = 0; static char *mr_logfile = NULL; /* Cleanup function for messages */ void mr_msg_close(void) { free(mr_logfile); mr_logfile = NULL; } /* Initialization function for messages */ void mr_msg_init(const char *configfile, int loglevel) { FILE *fout = NULL; int res = 0; asprintf(&mr_logfile,configfile); if ((fout = fopen(mr_logfile, "w")) == NULL) { fprintf(stderr,"Unable to write to %s\n",mr_logfile); fprintf(stderr,"Logging desactivated\n",mr_logfile); mr_msg_close(); } if ((res = fclose(fout)) != 0) { fprintf(stderr,"Unable to close %s\n",mr_logfile); } mr_loglevel = loglevel; } /* * Function that log a message. Not called directly * but through macros in mr_msg.h */ void _mr_msg(int debug, const char *file, const char *function, int line, const char *fmt, ...) { int i = 0; int res = 0; FILE *fout = NULL; va_list args; if (mr_logfile == NULL) { return; } if (debug <= mr_loglevel) { if ((fout = fopen(mr_logfile, "a")) == NULL) { fprintf(stderr,"Unable to append to %s\n",mr_logfile); return; } // add 2 spaces to distinguish log levels if (debug > 0) { for (i = 1; i < debug; i++) fprintf(fout, " "); fprintf(fout, "%s->%s#%d: ", file, function, line); } va_start(args, fmt); if (vfprintf(fout, fmt, args) < 0) { fprintf(stderr,"Unable to print to %s\n",mr_logfile); } va_end(args); fprintf(fout, "\n"); if ((res = fclose(fout)) != 0) { fprintf(stderr,"Unable to close %s\n",mr_logfile); } } } void mr_msg(int level, const char *format, ...) { va_list args; va_start(args, format); _mr_msg(level, __FILE__, __FUNCTION__, __LINE__, format, args); va_end(args); }