Chitika

Wednesday, October 26, 2011

C++: Minimal log - but complete

Definition:

#include <cstdio>
#include <cstring>
#include <ctime>
#include <cmath>

using namespace std;

#define max(x,y) x>y?x:y
 
 #define log(msg) logmsg(__FUNCTION__, msg)

FILE *logFile=NULL;
void logmsg(const char *funcName, const char *msg) {

        if(!logFile) {
                logFile = fopen("log.txt", "a+");
                setbuf(logFile, NULL);
        }

        int szFunc = max(30, strlen(funcName));
        int szMsg = max(60, strlen(msg));

        time_t tm_t=time(NULL);
        tm t;
        memcpy(&t, localtime(&tm_t), sizeof(tm));

        fprintf(logFile, "[%04d%02d%02d%02d%02d%02d] [%-*s] [%-*s]\n",
        t.tm_year+1900, t.tm_mon+1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec,
                szFunc, funcName, szMsg, msg
   );
}

Calling:

char tmp[1024];

sprintf(tmp, "for key (%s) value (%d)", key, value);
log(tmp);


No comments:

Post a Comment