1. 程式人生 > >程式中如何列印日誌?(三) VC++6.0和BCB6.0都不支援變長引數的巨集

程式中如何列印日誌?(三) 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__啊。

     睡覺了。