[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 |
|
---|
| 12 | #include <stdio.h>
|
---|
| 13 | #include <stdarg.h>
|
---|
| 14 |
|
---|
| 15 | static int mr_loglevel = 0;
|
---|
| 16 | static char *mr_logfile = NULL;
|
---|
| 17 |
|
---|
| 18 | /* Cleanup function for messages */
|
---|
| 19 | void mr_msg_close(void) {
|
---|
| 20 | free(mr_logfile);
|
---|
| 21 | mr_logfile = NULL;
|
---|
| 22 | }
|
---|
| 23 |
|
---|
| 24 | /* Initialization function for messages */
|
---|
| 25 | void mr_msg_init(const char *configfile, int loglevel) {
|
---|
| 26 | FILE *fout = NULL;
|
---|
| 27 | int res = 0;
|
---|
| 28 |
|
---|
| 29 | asprintf(&mr_logfile,configfile);
|
---|
| 30 | if ((fout = fopen(mr_logfile, "w")) == NULL) {
|
---|
| 31 | fprintf(stderr,"Unable to write to %s\n",mr_logfile);
|
---|
[1061] | 32 | fprintf(stderr,"Logging desactivated\n");
|
---|
[1054] | 33 | mr_msg_close();
|
---|
| 34 | }
|
---|
| 35 | if ((res = fclose(fout)) != 0) {
|
---|
| 36 | fprintf(stderr,"Unable to close %s\n",mr_logfile);
|
---|
| 37 | }
|
---|
| 38 | mr_loglevel = loglevel;
|
---|
| 39 | }
|
---|
| 40 |
|
---|
| 41 | /*
|
---|
| 42 | * Function that log a message. Not called directly
|
---|
[1061] | 43 | * but through other functions
|
---|
[1054] | 44 | */
|
---|
[1061] | 45 | void _mr_msg(int debug, const char *file, const char *function, int line, const char *fmt, va_list args) {
|
---|
[1054] | 46 |
|
---|
| 47 | int i = 0;
|
---|
| 48 | int res = 0;
|
---|
| 49 | FILE *fout = NULL;
|
---|
| 50 |
|
---|
| 51 | if (mr_logfile == NULL) {
|
---|
| 52 | return;
|
---|
| 53 | }
|
---|
| 54 |
|
---|
| 55 | if (debug <= mr_loglevel) {
|
---|
| 56 | if ((fout = fopen(mr_logfile, "a")) == NULL) {
|
---|
| 57 | fprintf(stderr,"Unable to append to %s\n",mr_logfile);
|
---|
| 58 | return;
|
---|
| 59 | }
|
---|
| 60 |
|
---|
| 61 | // add 2 spaces to distinguish log levels
|
---|
| 62 | if (debug > 0) {
|
---|
| 63 | for (i = 1; i < debug; i++)
|
---|
| 64 | fprintf(fout, " ");
|
---|
| 65 | fprintf(fout, "%s->%s#%d: ", file, function, line);
|
---|
| 66 | }
|
---|
| 67 | if (vfprintf(fout, fmt, args) < 0) {
|
---|
| 68 | fprintf(stderr,"Unable to print to %s\n",mr_logfile);
|
---|
[1061] | 69 | return;
|
---|
[1054] | 70 | }
|
---|
| 71 |
|
---|
| 72 | fprintf(fout, "\n");
|
---|
| 73 | if ((res = fclose(fout)) != 0) {
|
---|
| 74 | fprintf(stderr,"Unable to close %s\n",mr_logfile);
|
---|
| 75 | }
|
---|
| 76 | }
|
---|
| 77 | }
|
---|
| 78 |
|
---|
[1061] | 79 | void mr_msg(int level, const char *fmt, va_list args) {
|
---|
[1054] | 80 |
|
---|
[1061] | 81 | _mr_msg(level, __FILE__, __FUNCTION__, __LINE__, fmt, args);
|
---|
[1054] | 82 | }
|
---|