-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLogging.cpp
More file actions
273 lines (255 loc) · 8.64 KB
/
Copy pathLogging.cpp
File metadata and controls
273 lines (255 loc) · 8.64 KB
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
#include "logging.h"
#ifdef WIN32
#include <windows.h>
#endif // WIN32
#include "boost/filesystem.hpp"
#include "boost/filesystem/fstream.hpp"
#include <io.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
extern "C" void Log(void* p,int log_type, const char* fun, int line, char* msg, ...) {
char tmp[1024] = { 0 };
va_list pArg = NULL;
va_start(pArg, msg);
vsnprintf(tmp, sizeof(tmp), msg, pArg);
va_end(pArg);
((Logging*)p)->WriteMsg((eLogType)log_type, fun, line, tmp);
}
static eLogColor eLogColorArr[LOG_MAX] = { COLOR_GREEN,COLOR_PINK,COLOR_YELLOW,COLOR_RED};
#ifdef WIN32
// Returns the character attribute for the given color.
static WORD GetColorAttribute(eLogColor color) {
switch (color) {
case COLOR_RED: return FOREGROUND_RED;
case COLOR_GREEN: return FOREGROUND_GREEN;
case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
case COLOR_PINK: return FOREGROUND_BLUE | FOREGROUND_RED;
default: return 0;
}
}
#else
// Returns the ANSI color code for the given color.
static const char* GetAnsiColorCode(eLogColor color) {
switch (color) {
case COLOR_RED: return "1";
case COLOR_GREEN: return "2";
case COLOR_YELLOW: return "3";
case COLOR_DEFAULT: return "";
};
return NULL; // stop warning about return type.
}
#endif
Logging::Logging()
{
appName_ = string("using_boost");
::GetModuleFileNameA(0, appPath_, 256);
dump2File_count = 10;
dump2File_timeout = 1000;
}
Logging::~Logging()
{
for (auto i = 0; i < LOG_MAX; ++i) {
if (nullptr != files_[i]) {
fclose(files_[i]);
}
if (nullptr != buffers_[i])
{
delete buffers_[i];
}
}
delete logThread_;
}
namespace bfsys = boost::filesystem;
void Logging::InitLoggin()
{
PTIME nowTime = boost::posix_time::microsec_clock::local_time();
string curWorkStr = appPath_;
curWorkStr = curWorkStr.substr(0, curWorkStr.rfind("\\")) + "\\Log";
if (!bfsys::exists(curWorkStr)) {
boost::filesystem::create_directory(curWorkStr);
}
int n32Res = 0;
for (int i = LOG_INFO; i < LOG_MAX; ++i) {
files_[i] = NULL;
buffer_count[i] = 0;
preFlushTime[i] = nowTime;
n32Res = CreateLogFile((eLogType)i, curWorkStr);
if (n32Res != 0) {
printf("Createfile(%d) failed", i);
}
buffers_[i] = new thread_buffer(1024*10,1024);
}
//
logThread_ = ActiveThread::Create(std::bind(&Logging::BufferHandler,this,std::placeholders::_1));
logThread_->AddTimer(std::bind(&Logging::CheckBufferTimeout, this), dump2File_timeout, eTType_dline, true);
logThread_->Start();
}
int Logging::CreateLogFile(eLogType elogtype, string workDir)
{
string strPre;
switch (elogtype) {
case LOG_DEBUG:
strPre = "DEBUG";
break;
case LOG_INFO:
strPre = "INFO";
break;
case LOG_WARNNING:
strPre = "WARNNING";
break;
case LOG_ERROR:
strPre = "ERROR";
break;
default:
return -1;
}
char str[128];
int fd = -1;
bool ifReuseCurDay = true; //是否复用本日log文件,会覆盖
if (!ifReuseCurDay) {
std::string strTime = boost::posix_time::to_iso_string(boost::posix_time::microsec_clock::local_time()).c_str();
ConvertTime2String(strTime, true,true);
_snprintf(str, sizeof(str), "%s/%s-%s-%s.log", workDir.c_str(), appName_.c_str(), strPre.c_str(), strTime.c_str());
fd = open(str, O_WRONLY | O_CREAT | O_EXCL, 0664);
}
else {
std::string strTime = boost::gregorian::to_iso_string(boost::gregorian::day_clock::local_day());
ConvertTime2String(strTime, true,true);
_snprintf(str, sizeof(str), "%s/%s-%s-%s.log", workDir.c_str(), appName_.c_str(), strPre.c_str(), strTime.c_str());
fd = open(str, O_WRONLY | O_CREAT, _S_IREAD | _S_IWRITE | _S_IEXEC);
}
if (fd == -1) {
DWORD errorMessageID = ::GetLastError();
LPSTR messageBuffer = nullptr;
size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);
std::string message(messageBuffer, size);
//Free the buffer.
LocalFree(messageBuffer);
printf("%s create(%d) file error %s\n", __FUNCTION__, (int)elogtype, message.c_str());
return -1;
}
files_[elogtype] = fdopen(fd, "a");
if (NULL == files_[elogtype]) {
printf("%s open file(%d) failed\n", __FUNCTION__, (int)elogtype);
return -1;
}
return 0;
}
void Logging::CheckBufferTimeout()
{
FILE* pCurFile = nullptr;
for (size_t i = LOG_INFO; i < LOG_MAX; i++)
{
pCurFile = files_[i];
if (pCurFile == nullptr) {
continue;
}
thread_buffer* pDumpBuffer = buffers_[i];
if (pDumpBuffer->size() <= 0) {
continue;
}
fwrite(pDumpBuffer->GetData(pDumpBuffer->size()), 1, pDumpBuffer->size(), pCurFile);
fflush(pCurFile);
buffer_count[i] = 0;
preFlushTime[i] = boost::posix_time::microsec_clock::local_time();
}
}
void Logging::BufferHandler(buffer_base*& pBuffer)
{
if (pBuffer->GetType() != 2)
return;
logbuffer* log_buffer = (logbuffer*)pBuffer;
PTIME nowTime = boost::posix_time::microsec_clock::local_time();
string DateStr = boost::posix_time::to_iso_string(nowTime);
ConvertTime2String(DateStr);
memcpy(log_buffer->log_buffer, DateStr.c_str(), 19);
//
{//print
const eLogColor color = eLogColorArr[log_buffer->log_type];
#ifdef WIN32
const HANDLE stderr_handle = GetStdHandle(STD_ERROR_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO buffer_info;
GetConsoleScreenBufferInfo(stderr_handle, &buffer_info);
const WORD old_color_attrs = buffer_info.wAttributes;
fflush(stderr);
SetConsoleTextAttribute(stderr_handle,GetColorAttribute(color) | FOREGROUND_INTENSITY);
fwrite(log_buffer->log_buffer, 1, log_buffer->buffer_len, stderr);
fflush(stderr);
SetConsoleTextAttribute(stderr_handle, old_color_attrs);
#else
fprintf(stderr, "\033[0;3%sm", GetAnsiColorCode(color));
fwrite(message, len, 1, stderr);
fprintf(stderr, "\033[m"); // Resets the terminal to default.
#endif
}
//wirte log file
{
FILE* pCurFile = files_[log_buffer->log_type];
if (pCurFile == nullptr) {
return;
}
thread_buffer* pDumpBuffer = buffers_[log_buffer->log_type];
bool ifDump2File = pDumpBuffer->capacity() >= log_buffer->buffer_len;
if (ifDump2File && buffer_count[log_buffer->log_type] < dump2File_count) {
pDumpBuffer->append(log_buffer->log_buffer, log_buffer->buffer_len);
buffer_count[log_buffer->log_type]++;
}
else {
if (pDumpBuffer->size() > 0) {
fwrite(pDumpBuffer->GetData(pDumpBuffer->size()), 1, pDumpBuffer->size(), pCurFile);
}
fwrite(log_buffer->log_buffer, 1, log_buffer->buffer_len, pCurFile);
fflush(pCurFile);
buffer_count[log_buffer->log_type] = 0;
preFlushTime[log_buffer->log_type] = boost::posix_time::microsec_clock::local_time();
}
}
}
void Logging::Log(int log_type, const char* fun, int line, char* msg, ...)
{
char tmp[1024] = { 0 };
va_list pArg = NULL;
va_start(pArg, msg);
vsnprintf(tmp, sizeof(tmp), msg, pArg);
va_end(pArg);
WriteMsg((eLogType)log_type, fun, line, tmp);
}
void Logging::WriteMsg(eLogType elogtype, const char* fun, int line, char* msg)
{
char tmp[1024] = { 0 };
logbuffer sLogBuffer;
sLogBuffer.log_type = elogtype;
//中间留白,方便插入时间,对齐整洁一些
_snprintf(tmp, sizeof(tmp), " %d %s:%d %s\n", GetCurrentThreadId(), fun, line, msg);
sLogBuffer.add_buffer(tmp,strlen(tmp));
logThread_->Send(&sLogBuffer);
}
static string split_1 = string("-");
static string split_2 = string(":");
void Logging::ConvertTime2String(std::string& str, bool year, bool filename)
{
int pos = str.find('T');
if (pos < 0)
{
return;
}
if (!year) {
str.erase(0, 4);
pos -= 4;
}
else{
str.replace(4, 1, split_1);
}
str.replace(pos, 1, split_1);
if (filename) {
str.replace(pos + 3, 0, split_1);
str.replace(pos + 6, 0, split_1);
}
else {
str.replace(pos + 3, 0, split_2);
str.replace(pos + 6, 0, split_2);
}
str.replace(pos - 2, 0, split_1);
}