/* * $Id$ * * Code (c)2006 Bruno Cornec * * Main file of mr_msg : a very small and simple * library for messages management * * Provided under the GPLv2 */ #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include #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_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 other functions */ 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; } va_start(args,fmt); // 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); } if (vfprintf(fout, fmt, args) < 0) { fprintf(stderr,"Unable to print to %s\n",mr_logfile); } fprintf(fout, "\n"); if ((res = fclose(fout)) != 0) { fprintf(stderr,"Unable to close %s\n",mr_logfile); } va_end(args); } } void mr_msg(int level, const char *fmt, ...) { va_list args; va_start(args,fmt); _mr_msg(level, __FILE__, __FUNCTION__, __LINE__, fmt, args); va_end(args); }