// stllogfile.cpp
#include "stllogfile.h" #include <time.h>
STLLogFile::STLLogFile(const char *szFileName) { m_szFileName = NULL; ::InitializeCriticalSection(&m_csLock); SetFileName(szFileName); }
STLLogFile::~STLLogFile() { Close(); if (m_szFileName) { delete [] m_szFileName; } ::DeleteCriticalSection(&m_csLock); }
void STLLogFile::SetFileName(const char *szFileName) { if (szFileName == NULL) return;
if (m_szFileName) { delete [] m_szFileName; m_szFileName = NULL; }
Close(); int bufSize = strlen(szFileName) + 1; m_szFileName = new char[strlen(szFileName) + 1]; if (m_szFileName) { memset(m_szFileName, 0, sizeof(m_szFileName)); sprintf_s(m_szFileName, bufSize, "%s", szFileName); //memcpy(m_szFileName, szFileName, strlen(szFileName));
} }
const char *STLLogFile::GetFileName() { return m_szFileName; }
void STLLogFile::Close() { if (IsOpen()) { m_file.close(); } }
bool STLLogFile::IsOpen() { if (m_file) { if (m_file.is_open()) return true; } return false; //return !m_file && m_file.is_open();
}
void STLLogFile::AddLog(LPCVOID lpBuffer, DWORD dwLength) { if (!lpBuffer) return;
__try { Lock(); if (OpenFile()) { WriteLog(lpBuffer, dwLength); } } __finally { UnLock(); } }
void STLLogFile::Lock() { ::EnterCriticalSection(&m_csLock); }
void STLLogFile::UnLock() { ::LeaveCriticalSection(&m_csLock); }
bool STLLogFile::OpenFile() { if (IsOpen()) return true; if (!m_szFileName) return false; m_file.open(m_szFileName, ios::in | ios::out | ios::app); //m_file.seekp(0, ios::end);
return IsOpen(); }
unsigned long STLLogFile::Write(LPCVOID lpBuffer, unsigned long dwLength) { unsigned long ulWriteLength = 0; if (IsOpen()) { m_file << lpBuffer << std::endl; ulWriteLength = dwLength; } return ulWriteLength; }
void STLLogFile::WriteLog( LPCVOID lpBuffer, unsigned long dwLength) { time_t now; char temp[24]; unsigned long ulWriteLength = 0;
if (IsOpen()) { time(&now); strftime(temp, 20, "%Y-%m-%d %H:%M:%S", localtime(&now)); m_file << temp << " "; ulWriteLength = dwLength; m_file << (const char *)lpBuffer << std::endl; m_file.flush(); } }
void STLLogFile::Log(const char * szString, ...) { char szEntry[1024]; va_list args; va_start(args, szString); vsprintf(szEntry, szString, args); AddLog(szEntry, strlen(szEntry)); }
|