[code]
//////////////////////////////////////////////////////////////////////////
// EventLog Class
// by DangerD (DangerD@live.com)
//////////////////////////////////////////////////////////////////////////
// EventLog.h
#ifndef EVENTLOGGER_H
#define EVENTLOGGER_H
#include <string>
#include <fstream>
class EventLogger
{
public:
EventLogger(); // constructor
~EventLogger(); // ~destructor
std::wstring FilePath();
bool FindFilePath(HMODULE hModule);
void ReplaceFileExt(std::wstring& FilePath,
const std::wstring& NewExt);
void ReplaceFileName(std::wstring& FilePath,
const std::wstring& NewName);
bool OpenFile(const std::wstring& FilePath);
std::string GetTime();
void LogEvent(const std::string& Event);
private:
std::wstring m_FilePath;
std::string m_Time;
std::ofstream m_File;
};
#endif
// end of file
//////////////////////////////////////////////////////////////////////////
[/code]
[code]
//////////////////////////////////////////////////////////////////////////
// EventLog Class
// by DangerD (DangerD@live.com)
//////////////////////////////////////////////////////////////////////////
// EventLog.cpp
#include <Windows.h>
#include <tchar.h>
#include <time.h>
//---
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
//---
#include "EventLogger.h"
// constructor
EventLogger::EventLogger()
{
}
// ~destructor
EventLogger::~EventLogger()
{
m_File.close();
}
std::wstring EventLogger::FilePath()
{
return m_FilePath;
}
bool EventLogger::FindFilePath(HMODULE hModule)
{
std::vector<TCHAR> Path(MAX_PATH);
if(!GetModuleFileName(hModule, &Path[0], Path.size())) {
// you can change this for however your program handles errors
std::wcerr << _T("Error: Couldn't get file path.") << std::endl;
return false;
}
m_FilePath = &Path[0];
return true;
}
void EventLogger::ReplaceFileExt(std::wstring& FilePath,
const std::wstring& NewExt)
{
int Length = FilePath.length();
int FileExt = Length - 4;
FilePath.replace(FileExt, Length, NewExt);
m_FilePath = FilePath;
}
void EventLogger::ReplaceFileName(std::wstring& FilePath,
const std::wstring& NewName)
{
int Pos = FilePath.rfind(_T("\\")); ++Pos;
FilePath.erase(Pos, std::string::npos);
FilePath.append(NewName);
m_FilePath = FilePath;
}
bool EventLogger::OpenFile(const std::wstring& FilePath)
{
m_File.open(FilePath.c_str(), std::ios::out | std::ios::app);
if (!m_File) {
// you can change this for however your program handles errors
std::wcerr << _T("Error: Couldn't open file!") << std::endl;
return false;
}
return true;
}
std::string EventLogger::GetTime()
{
time_t rawtime;
struct tm timeinfo;
std::vector<char> Time(MAX_PATH);
time(&rawtime);
localtime_s(&timeinfo, &rawtime);
strftime(&Time[0], Time.size(),"%I:%M%p-> ", &timeinfo);
m_Time = &Time[0];
return m_Time;
}
void EventLogger::LogEvent(const std::string& Event)
{
GetTime();
m_File << m_Time << Event << std::endl;
}
// end of file
//////////////////////////////////////////////////////////////////////////
[/code]