windows 下最简单的日志函数 writelog

//文件名: Log.h
#ifndef LOGWXN_H_INCLUDED

#define LOGWXN_H_INCLUDED


#include
#include
#include


#include
#include


#define LOG_FILE "mylog.log"
#define BUFF_MAX_LENGTH 512


int WrtLog(int LogLevel, char * format, ...)
{
    char sbuff[BUFF_MAX_LENGTH];
    char sTmpStr[BUFF_MAX_LENGTH] = "";
    char sEnter[2] = "";


    struct tm t;
    time_t now;
    int year;


    va_list *ap;
    FILE *fh;
    sbuff[0] = '\0';




    if ((fh = fopen(LOG_FILE, "a+")) == NULL)
    {
        perror("Create or Open LogFile Error!\n");
        return -1;
    }
    else
    {
        ap = (va_list *)
             malloc(sizeof(va_list));
        if (ap != NULL)
        {
            va_start(*ap, format);
#ifdef WIN32
            _vsnprintf(sbuff, BUFF_MAX_LENGTH, format, *ap);
#else
            vsnprintf(sbuff, BUFF_MAX_LENGTH, format, *ap);
#endif
            va_end(*ap);
            free(ap);
        }
        if (sbuff[strlen(sbuff) - 1] != '\n')
            strcpy(sEnter, "\n");


        time(&now);
        t =  *localtime(&now);
        year = t.tm_year;
        if (year < 50)
            year += 2000;
        else
            year += 1900;
        sprintf(sTmpStr,"%04d-%02d-%02d %02d:%02d:%02d ",year,t.tm_mon+1,t.tm_mday,t.tm_hour,t.tm_min,t.tm_sec);
        fprintf(fh, "%s %s%s", sTmpStr, sbuff, sEnter);
        fclose(fh);
    }
    return 0;
}




#endif // LOGWXN_H_INCLUDED


//文件名:main.c

#include
#include
#include


#include "Logwxn.h"


int main()
{
    WrtLog(2,"wuyeyixi:,,,%d,,,%d,,,%s", 25, 25, "dph");
    return 0;
}

你可能感兴趣的:(C++,windows,C,windows,list,file,null,struct)