-
Notifications
You must be signed in to change notification settings - Fork 1
/
logfile.cpp
80 lines (69 loc) · 1.84 KB
/
logfile.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include "logfile.h"
LogFile::LogFile()
{
RollFile();
}
LogFile::~LogFile()
{
Close();
}
void LogFile::GetFileName(time_t nowTime, std::string & sLogName)
{
struct tm * stTime = gmtime(&nowTime);
sLogName.resize(19);
strftime(const_cast<char *> (sLogName.data()), sLogName.capacity(), "%Y%m%d-%H%M%S.log", stTime);
}
void LogFile::RollFile()
{
time_t nowTime = time(NULL);
std::string sLogName;
GetFileName(nowTime, sLogName);
m_ptWriteFile.reset(new WriteFile(sLogName));
m_cnt = 0;
m_writedSize = 0;
m_lastFlushTime = nowTime;
m_lastRollTime = nowTime;
}
void LogFile::Append(const char * data, size_t writeSize)
{
// FIX ME if writeSize is larger than kRollFileSize, will cause wrong
if (m_writedSize > kRollFileSize - writeSize)
{
//std::cout << "RollFile " << __FILE__ << " " << __LINE__ << " " << __func__ << " " << m_writedSize << " " << std::endl;
RollFile();
}
m_ptWriteFile->Append(data, writeSize);
m_writedSize += writeSize;
m_cnt += 1;
//std::cout << __FILE__ << " " << __LINE__ << " " << __func__ << " " << m_cnt << " " << m_writedSize << std::endl;
if (kCheckNSteps < m_cnt)
{
time_t nowTime = time(NULL);
time_t nextStartTime = nowTime / kRollPerSeconds * kRollPerSeconds;
// next day shoule roll log file
if (m_lastRollTime < nextStartTime)
{
//std::cout << "RollFile " << __FILE__ << " " << __LINE__ << " " << __func__ << " " << nowTime << " " << m_lastFlushTime << std::endl;
RollFile();
}
else if (kFlushInteralSeconds < nowTime - m_lastFlushTime)
{
//std::cout << "Flush " << __FILE__ << " " << __LINE__ << " " << __func__ << " " << nowTime << " " << m_lastFlushTime << std::endl;
Flush();
m_lastFlushTime = nowTime;
}
m_cnt = 0;
}
}
void LogFile::Flush()
{
m_ptWriteFile->Flush();
}
void LogFile::Sync()
{
m_ptWriteFile->Sync();
}
void LogFile::Close()
{
m_ptWriteFile->Close();
}