简单的日志定位系统----读取exe执行文件路径下指定格式的文件内容,根据日志关键字输出指定结果,实现简单问题定位
步骤很简单:
1、clock()函数,用来计时,看性能几何
2、动态获取当前执行文件路径
3、分割'路径'字符串,再重新组装,boost库有现成的split函数,也可以用stroke函数自己实现
4、类型转换,路径要换成wstring类型
5、找寻路径下指定格式的所有文件
6、读取文件内容放入缓存
7、业务逻辑处理,根据日志关键字输出指定结果
8、结束
下面代码只是最原始的,业务逻辑处理没有示例,代码本身也是面向程序的,有很多地方为了易懂,有点重复,只是实现了其功能
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <windows.h>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp> //is_any_of
using namespace std;
int main()
{
clock_t Tstart,Tend;
Tstart = clock();
string strPath; //动态执行程序路径
vector<string> everyPath; //存放每一级目录
string sPath = ""; //拼装后string路径
wstring wsPath = L""; //wstring完整路径
wstring wsFullPath = L""; //wstring完整路径和文件名(实际是*的文件名)
wstring wsTrueFullPath = L""; //wstring真正完整路径和文件名
vector<wstring> vecEveryFile; //某目录下的所有指定格式的文件
vector<wstring> vecFullFile; //满足条件的文件名的绝对路径
vector<string> vecFileContent; //存放每一级目录
string strFileContent;
int nFileCount = 0;
char chpath[100];
GetCurrentDirectory(MAX_PATH,chpath);
strPath = chpath;
cout << strPath << endl;
boost::split(everyPath,strPath,boost::is_any_of(",\\"),boost::token_compress_on);
for(vector<string>::iterator iter= everyPath.begin();iter!= everyPath.end();iter++)
{
string stempPath = *iter;
sPath = sPath + stempPath + "\\" + "\\" ;
}
cout << sPath << endl;
const char* chPath = sPath.c_str();
size_t iPathNum = strlen(chPath) +1 ;
const size_t newSize = 100;
size_t convertedChars = 0;
wchar_t wNewstring[newSize];
mbstowcs_s(&convertedChars,wNewstring,iPathNum,chPath,_TRUNCATE);
wsPath = wNewstring;
wcout << wsPath << endl;
wsFullPath = wsPath + L"*.log";
wcout << wsFullPath << endl;
_wfinddata_t fileInfo;
long handle = _wfindfirst(wsFullPath.c_str(),&fileInfo);
if( -1 == handle)
{
cout << nFileCount << endl;
Tend = clock();
double duration = (double)(Tend - Tstart);
cout << "can not find the log" << endl;
cout << duration << endl;
return 0;
}
do
{
nFileCount ++;
wstring wTempFile = fileInfo.name;
vecEveryFile.push_back(wTempFile);
}while( _wfindnext(handle,&fileInfo)==0 );
cout << nFileCount << endl;
for(vector<wstring>::iterator iter = vecEveryFile.begin();iter != vecEveryFile.end();iter ++)
{
wstring wtempFilename1 = *iter;
wstring wFullFileName = wsPath+wtempFilename1;
vecFullFile.push_back(wFullFileName);
}
for(vector<wstring>::iterator iter = vecFullFile.begin();iter != vecFullFile.end();iter ++)
{
ifstream infile(*iter);
while( infile >> strFileContent)
{
vecFileContent.push_back(strFileContent);
}
}
//这边只是查看exe路径下的文件内容是否全部读取到缓存,实际的话根绝日志关键字输出不同的内容既可以
for(vector<string>::iterator iter = vecFileContent.begin();iter != vecFileContent.end();iter ++)
{
cout << *iter << endl;
}
Tend = clock();
double duration = (double)(Tend - Tstart);
cout << duration << endl;
system("PAUSE");
return 0;
}
在file.exe的路劲下放入了alarm.log和trap.log,内容如下
file.exe的执行结果如下,成功将俩个日志文件的内容读入到缓存中,真正的日志定位系统还要实现对缓存内数据的处理,根据不同的值要输出不同的值到界面,让看不懂日志的人只需要执行一下exe文件,直接看输出就可以