因为上课的缘故,老师让我们用c++编一个log库,有以下要求
A、日志的输出格式为:[2013-04-17 12:23:17] [DEBUG] file no find
B、日志文件在超过1K大小后,自动新建一个日志文件。
C、当日志文件超过10个后,自动从第一个日志文件重新记录。
java用惯了,c++就是麻烦啊。闲来无事发到网上吧,说不定谁会有用呢先是得到时间的头文件
/*
* getTime.h
*
* Created on: 2013-4-25
* Author: sun
*/
#if !defined(IOSTREAM_INCLUDED)
#include <iostream>
#endif
#if !defined(TIME_H_INCLUDED)
#include <time.h>
#endif
#if !defined(STRING_INCLUDED)
#include <string>
#endif
#if !defined(SSTREAM_INCLUDED)
#include <sstream>
#endif
using namespace std;
string getTime() {
time_t timep;
struct tm *p_tm;
timep = time(NULL);
p_tm = localtime(&timep); /*获取本地时区时间*/
string str;
ostringstream os;
os<<'['<<p_tm->tm_year+1900<<'-'<<p_tm->tm_mon+1<<'-'<<p_tm->tm_mday<<' '<<
p_tm->tm_hour<<':'<<p_tm->tm_min<<':'<<p_tm->tm_sec<<']';
return os.str();
}
这是主要的MyLog类,因为没有牵涉到具体的程序,所以还不是很完整,不过上面的要求是达到了的
/*
* Log.h
*
* Created on: 2013-4-25
* Author: sun
*/
#if !defined(GETTIME_H_INCLUDED)
#include "getTime.h"
#endif
#if !defined(FSTREAM_INCLUDED)
#include <fstream>
#endif
using namespace std;
class MyLog {
private:
string filepath;
int disp_level;
int lognumber;
bool clear;
public:
void writeLog(int level, string str);
MyLog(int disp_level, string filepath, int lognumber);
};
MyLog::MyLog(int disp_level, string filepath, int lognumber) {
this->disp_level = disp_level;
this->filepath = filepath;
this->lognumber = lognumber;
this->clear = false;
}
void MyLog::writeLog(int level, string str) {
//判断,若level小鱼disp_level,则不予输出
if (level < disp_level) {
return;
}
//生成输出日志的string
ostringstream os;
os<<getTime()<<" [DEBUG] "<<str;
string ostr = os.str();
fstream ioFile;
string temp = filepath;
//判断,若clear=false,则照常打开日志文件,从末尾开始添加,若clear=true,则清空文件,从头开始添加
if(!clear) {
ioFile.open(temp.append(1,'0'+lognumber).c_str(),ios::out|ios::app);
}else {
ioFile.open(temp.append(1,'0'+lognumber).c_str(),ios::out|ios::trunc);
clear = false;
}
//判断,如果文件读取失败则报错!
if(!ioFile) {
cout<<"open error!"<<endl;
return;
}
//读取文件指针的位置,从而得到文件大小
streampos ps = ioFile.tellg();
cout << "File size: " << ps << endl;
//判断如果文件大小大于1024即1K,那么就将log编号加1,如果大于9则回到0,且每次变化后都使clear=true
if(ps > 1024) {
lognumber++;
if (lognumber > 9) {
lognumber = 0;
}
clear = true;
//重新调用writeLog函数,且将原来的fstream关闭
writeLog(level, str);
ioFile.close();
return;
}
//将日志写入日志文件
ioFile<<ostr<<endl;
ioFile.close();
cout<<"write \""<<ostr<<"\" to \""<<temp<<"\""<<endl;
}
最后写个主函数测试一下
/*
* main.cpp
*
* Created on: 2013-4-25
* Author: sun
*/
#include "MyLog.h"
using namespace std;
int main(void) {
MyLog* mylog = new MyLog(1,"/home/sun/log",0);
int i;
for(i=0;i<11;i++) {
mylog->writeLog(1,"my log!");
}
delete(mylog);
return 0;
}
因为不怎么登csdn,若有问题请发我的邮箱:sxf20778@gmail.com