-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathlog_file.cpp
131 lines (114 loc) · 2.43 KB
/
log_file.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#include "log_file.h"
#include "file_util.h"
#include <assert.h>
#include <stdio.h>
#include <time.h>
using namespace ydx;
LogFile::LogFile(size_t rollSize,
const std::string& basename,
bool threadSafe,
int flushInterval,
int checkEveryN)
: basename_(basename),
rollSize_(rollSize),
flushInterval_(flushInterval),
checkEveryN_(checkEveryN),
count_(0),
mutex_(threadSafe ? new MutexLock : NULL),
startOfPeriod_(0),
lastRoll_(0),
lastFlush_(0)
{
assert(basename.find('/') == std::string::npos);
if(basename.empty())
{
char buf[128];
int n = readlink("/proc/self/exe" , buf , sizeof(buf));
(void)n;
basename_ = ::basename(buf);
}
rollFile();
}
LogFile::~LogFile()
{
}
void LogFile::flush()
{
if (mutex_)
{
MutexLockGuard lock(*mutex_);
file_->flush();
}
else
{
file_->flush();
}
}
void LogFile::append(const char* logline, int len)
{
if (mutex_)
{
MutexLockGuard lock(*mutex_);
append_unlocked(logline, len);
}
else
{
append_unlocked(logline, len);
}
}
void LogFile::append_unlocked(const char* logline, int len)
{
file_->append(logline, len);
if (file_->writtenBytes() > rollSize_) //一个文件最多写rollSize_字节,默认1M
{
rollFile();
}
else
{
++count_;
if (count_ >= checkEveryN_) //
{
count_ = 0;
time_t now = ::time(NULL);
time_t thisPeriod_ = now / kRollPerSeconds_ * kRollPerSeconds_;
if (thisPeriod_ != startOfPeriod_) //一个文件最多写startOfPeriod_时间默认24小时
{
rollFile();
}
else if (now - lastFlush_ > flushInterval_) //超过3秒刷新一次
{
lastFlush_ = now;
file_->flush();
}
}
}
}
bool LogFile::rollFile()
{
time_t now = 0;
std::string filename = getLogFileName(basename_, &now);
time_t start = now / kRollPerSeconds_ * kRollPerSeconds_;
if (now > lastRoll_)
{
lastRoll_ = now;
lastFlush_ = now;
startOfPeriod_ = start; //startOfPeriod_为整天
file_.reset(new AppendFile(filename));
return true;
}
return false;
}
std::string LogFile::getLogFileName(const std::string& basename, time_t* now)
{
std::string filename;
filename.reserve(basename.size() + 64);
filename = basename;
char timebuf[32];
struct tm tm;
*now = time(NULL);
localtime_r(now, &tm); // FIXME: localtime_r ?
strftime(timebuf, sizeof timebuf, ".%Y%m%d-%H%M%S", &tm);
filename += timebuf;
filename += ".log";
return filename;
}