/* * $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; /* * This function is in the lowest part of the tree * It should not depend on any other function of the mr lib */ /* Cleanup function for messages */ void mr_msg_close(void) { free(mr_logfile); mr_logfile = NULL; mr_loglevel = 0; } /* Initialization function for messages */ void mr_msg_init(const char *logfile, int loglevel) { FILE *fout = NULL; int res = 0; asprintf(&mr_logfile,logfile); 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 * fmt needs to be just before ... * debug should be >0 to have file and line printed (real debug) * If =0 it's an informative log message */ void mr_msg_int(int debug, int line, const char *file, 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 #%d: ", file, line); } va_start(args,fmt); if (vfprintf(fout, fmt, args) < 0) { fprintf(stderr,"Unable to print to %s\n",mr_logfile); } fprintf(fout,"\n"); va_end(args); if ((res = fclose(fout)) != 0) { fprintf(stderr,"Unable to close %s\n",mr_logfile); } } }