短小的日志类 和用cout<<"A"<<B<<"/n"一样 支持 cout<<"A"<<B<<endl;
如果需要 可以自己重载<<
#include "VString.h"
#include <fstream>
#include <iostream>
/*
功能:写日志的类
作者:wangzhongwei
EMAIL:wzw200@sina.com
典型 用法:
MyLog Logout("Server.log");
int a=1;
char b[]="bb";
double d=0.5;
Logout<<a<<b<<d<<endl;
其中打印一行后必须以endl或者 "/n"结尾
否则出错
*/
class MyLog
{
public:
MyLog(char *LogFilepath);
~MyLog(){};
MyLog& operator<<(char * s);
MyLog& operator<<(int s);
MyLog& operator<<(double s);
MyLog& operator<<(VString s);
MyLog& operator<<(basic_ostream<char, char_traits<char> >& (*_Pfn)(basic_ostream<char, char_traits<char> >&))
{ // write endl to log using _Pfn 重载endl
Logout.open(Path,ios::app);
if(IsTime)
{
IsTime=false;
Logout<<GetTime()<<":";
}
IsTime=true;
Logout<<"/n";
Logout.close();
return (*this);
}
private:
bool IsTime;
ofstream Logout;
char Time[50];
char Path[1024];
char* GetTime();
};
#endif
//.cpp
#include "MyLog.h"
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
#ifdef _WIN32
#include<Windows.h>
#include <time.h>
#endif
MyLog::MyLog(char *LogFilepath)
{
memset(Path,'/0',1024);
strcat(Path,LogFilepath);
//cout<<Path<<endl;
IsTime=true;
}
char* MyLog::GetTime()
{
#ifdef _WIN32
SYSTEMTIME st;
GetLocalTime(&st);
sprintf(Time,"%d-%d-%d %d:%d:%d",st.wYear, st.wMonth ,st.wDay,st.wHour ,st.wMinute,st.wSecond);
return Time;
#else
time_t timep;
struct tm *p;
time(&timep);
p=localtime(&timep); //get server's time
if(p==NULL)
{
return NULL;
}
//create specific datetime format
sprintf(Time,"%d-%d-%d %d:%d:%d",p->tm_year+1900, p->tm_mon+1 ,p->tm_mday ,p->tm_hour ,p->tm_min,p->tm_sec);
return Time;
#endif
return 0;
}
MyLog& MyLog::operator<<(char * s)
{
Logout.open(Path,ios::app);
if(IsTime)
{
IsTime=false;
Logout<<GetTime()<<":";
}
if(strcmp(s,"/n")==0)
IsTime=true;
Logout<<s;
Logout.close();
return (*this);
}
MyLog& MyLog::operator<<(int s)
{
Logout.open(Path,ios::app);
if(IsTime)
{
IsTime=false;
Logout<<GetTime()<<":";
}
Logout<<s;
Logout.close();
return (*this);
}
MyLog& MyLog::operator<<(double s)
{
Logout.open(Path,ios::app);
if(IsTime)
{
IsTime=false;
Logout<<GetTime()<<":";
}
Logout<<s;
Logout.close();
return (*this);
}
MyLog& MyLog::operator<<(VString s)
{
Logout.open(Path,ios::app);
if(IsTime)
{
IsTime=false;
Logout<<GetTime()<<":";
}
Logout<<(char *)s;
Logout.close();
return (*this);
}
//test
#include "MyLog.h"
using namespace std;
int main()
{
MyLog Logout("1.log");
Logout<<"A"<<"B"<<"/n";
Logout<<"CC"<<123456<<"/n";
Logout<<endl;
Logout<<"d"<<"/n";
double a=0.5;
int b=5;
char aa[10]="aabb";
VString vs="ddee";
logout<<"double="<<a<<" int="<<b<<" char aa="<<aa<<" VString="<<20<<endl<<"eeffggg"<<endl;
int i=0;
return 1;
}