程序中如何打印日志?(三) VC++6.0和BCB6.0都不支持变长参数的宏

       接着前面的来讲。但是遗憾的是,无论是VC++6.0还是BCB6.0, 都不支持变长参数的宏,所以在这种环境下,无法彻底解决之前的问题(在VS2005中可以)。既然如此,我们只能求其次了,还是利用变成参数的函数来迂回解决吧:

//---------------------------------------------------------------------------

#ifndef Unit1H
#define Unit1H
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>

#define POS __FUNC__, __LINE__, __FILE__

//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published:	// IDE-managed Components
    TButton *Button1;
    TButton *Button2;
    void __fastcall Button2Click(TObject *Sender);
    void __fastcall Button1Click(TObject *Sender);
private:	// User declarations
public:		// User declarations
    __fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif


 

//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop
#include <wtypes.h>
#include <stdio.h>
#include <fstream>
#include <string>
using namespace std;


#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;


void log(char *function, int line, char *file, char *format, ...)
{
	va_list args;
	va_start(args, format);
	char buf[1024] = {0};
	vsprintf(buf, format, args);
	va_end(args);

    SYSTEMTIME stCurTime = {0};
    GetLocalTime(&stCurTime);
    char szTime[128] = {0};
    sprintf(szTime, "%d-%d-%d %d:%d:%d", stCurTime.wYear, stCurTime.wMonth, stCurTime.wDay, stCurTime.wHour, stCurTime.wMinute, stCurTime.wSecond);

    char szLocation[2048] = {0};
    sprintf(szLocation, "%s ===> Function--->%s, Line: %d, File: %s", buf, function, line, file);

    char szLog[2048] = {0};
    sprintf(szLog, "%s %s ", szTime, szLocation);
    ofstream outfile("log.txt", ios::app);
    outfile << szLog << endl;
}

//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
    : TForm(Owner)
{

}
//---------------------------------------------------------------------------

void __fastcall TForm1::Button1Click(TObject *Sender)
{
    log(POS, "HELLO");
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Button2Click(TObject *Sender)
{
    int a = 1;
    log(POS, "WORLD%d", a);
}
//---------------------------------------------------------------------------

     最后说一句,如果支持变成参数的宏,那该多好啊, 那时,POS都不用写。VS2005就可以,有__VA_ARGS__啊。

     睡觉了。

你可能感兴趣的:(程序中如何打印日志?(三) VC++6.0和BCB6.0都不支持变长参数的宏)