使用时, 请将zp_log.h和zp_log.cpp复制到你的程序目录, 并在代码中#include "zp_log.h"
ZPLog类概述:
创建ZPLog对象后, 将根据当前日期时间信息构造log文件名, 然后用户可以使用<<操作符输出自己的日志信息, 跟C++的cout<<差不多. 当日志的行数达到某个数量时(默认为10000), 将产生新文件名.
ZPLog类函数:
ZPLog()
默认构造函数, 输出目录为C:/, 最大行数为10000
ZPLog(int line)
输出目录为C:/, 最大行数由line指定
ZPLog(const char* sDir)
输出目录为sDir, 声明语法为ZPLog log("D://logs//"); 不要忘记后面的//, 最大行数为10000
ZPLog(const char* sDir, int line)
输出目录为sDir, 最大行数为line
ZPLog& operator << (const char *pLog)
输出日志, 用法为log << "system error";
如果使用log << "1111" << "2222"; 则日志文件中产生两行: 1111和2222.
void SetOutDir(const char* sDir)
指定输出目录
void SetMaxLine(int line)
指定最大行数, 超过最大行数, 将建立新日志, 用法为 log.SetMaxLine(10000);
zp_log.h
#ifndef ZP_LOG_H_
#define ZP_LOG_H_
//---------------------------------------------------------------------------
//#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
using namespace std;
const int LIMIT = 200;
class ZPLog
{
private:
string dir;
string fname;
int maxline;
private:
int Lines();
void MakeName();
public:
ZPLog();
ZPLog(int line);
ZPLog(const char* sDir);
ZPLog(const char* sDir, int line);
~ZPLog();
ZPLog& operator << (const char* pLog);
void SetOutDir(const char* sDir) { dir = sDir; MakeName(); }
void SetMaxLine(int line) { maxline = line; }
};
//---------------------------------------------------------------------------
#endif
zp_log.cpp
ZPLog::ZPLog()
{
dir = "C://";
maxline = 10000;
MakeName();
}
ZPLog::ZPLog(int line)
{
dir = "C://";
maxline = line;
MakeName();
}
ZPLog::ZPLog(const char *sDir)
{
dir = sDir;
maxline = 10000;
MakeName();
}
ZPLog::ZPLog(const char* sDir, int line)
{
dir = sDir;
maxline = line;
MakeName();
}
ZPLog::~ZPLog()
{
}
void ZPLog::MakeName()
{
// 以当前时间为log文件名
time_t t = time(NULL);
struct tm *pt = localtime(&t);
char str[LIMIT] = {'/0'};
strftime(str, LIMIT-1, "%Y%m%d%H%M%S.log", pt);
fname = dir + str;
//cout << fname << endl; //debug
}
int ZPLog::Lines()
{
int count = 0;
ifstream ipf(fname.c_str(), ios_base::in);
string str;
while(getline(ipf, str)) count++;
ipf.close();
return count;
}
ZPLog& ZPLog::operator << (const char* pLog)
{
if(Lines() >= maxline)
{
MakeName();
}
ofstream opf(fname.c_str(), ios_base::out | ios_base::app);
if(!opf.is_open()) return *this;
opf << pLog << endl;
opf.close();
return *this;
}
测试类:
int main()
{
ZPLog log;
for(int i=0; i<15000; ++i) log << "test";
ZPLog log2(2000);
for(int i=0; i<3000; ++i) log2 << "test";
ZPLog log3("D://Logs//");
for(int i=0; i<15000; ++i)
log3 << "test";
ZPLog log4("D://Logs//", 2000);
for(int i=0; i<3000; ++i) log4 << "test";
ZPLog log5;
log5.SetOutDir("D://Logs//");
log5.SetMaxLine(2000);
for(int i=0; i<3000; ++i) log5 << "test";
getchar();
return 0;
}