forked from facebook/watchman
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Logging.cpp
252 lines (214 loc) · 6.19 KB
/
Logging.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
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
/* Copyright 2012-present Facebook, Inc.
* Licensed under the Apache License, Version 2.0 */
#include <array>
#include <limits>
#include <sstream>
#ifdef __APPLE__
#include <pthread.h>
#endif
#include <folly/Optional.h>
#include <folly/ScopeGuard.h>
#include <folly/ThreadLocal.h>
#include <folly/system/ThreadName.h>
#include "Logging.h"
using namespace watchman;
static folly::ThreadLocal<folly::Optional<std::string>> threadName;
static constexpr size_t kMaxFrames = 64;
namespace {
template <typename String>
void write_stderr(const String& str) {
w_string_piece piece = str;
ignore_result(::write(STDERR_FILENO, piece.data(), piece.size()));
}
template <typename String, typename... Strings>
void write_stderr(const String& str, Strings&&... strings) {
write_stderr(str);
write_stderr(strings...);
}
} // namespace
static void log_stack_trace(void) {
#if defined(HAVE_BACKTRACE) && defined(HAVE_BACKTRACE_SYMBOLS)
std::array<void*, kMaxFrames> array;
size_t size;
char** strings;
size_t i;
size = backtrace(array.data(), array.size());
strings = backtrace_symbols(array.data(), size);
write_stderr("Fatal error detected at:\n");
for (i = 0; i < size; i++) {
write_stderr(strings[i], "\n");
}
free(strings);
#endif
}
namespace watchman {
namespace {
struct levelMaps {
// Actually a map of LogLevel, w_string, but it is relatively high friction
// to define the hasher for an enum key :-p
std::unordered_map<int, w_string> levelToLabel;
std::unordered_map<w_string, LogLevel> labelToLevel;
levelMaps()
: levelToLabel{{ABORT, "abort"},
{FATAL, "fatal"},
{ERR, "error"},
{OFF, "off"},
{DBG, "debug"}} {
// Create the reverse map
for (auto& it : levelToLabel) {
labelToLevel.insert(
std::make_pair(it.second, static_cast<LogLevel>(it.first)));
}
}
};
// Meyers singleton for holding the log level maps
levelMaps& getLevelMaps() {
static levelMaps maps;
return maps;
}
} // namespace
const w_string& logLevelToLabel(LogLevel level) {
return getLevelMaps().levelToLabel.at(static_cast<int>(level));
}
LogLevel logLabelToLevel(const w_string& label) {
return getLevelMaps().labelToLevel.at(label);
}
Log::Log()
: errorPub_(std::make_shared<Publisher>()),
debugPub_(std::make_shared<Publisher>()) {
setStdErrLoggingLevel(ERR);
}
Log& getLog() {
static Log log;
return log;
}
char* Log::timeString(char* buf, size_t bufsize, timeval tv) {
struct tm tm;
#ifdef _WIN32
time_t seconds = (time_t)tv.tv_sec;
tm = *localtime(&seconds);
#else
localtime_r(&tv.tv_sec, &tm);
#endif
char timebuf[64];
strftime(timebuf, sizeof(timebuf), "%Y-%m-%dT%H:%M:%S", &tm);
snprintf(buf, bufsize, "%s,%03d", timebuf, (int)tv.tv_usec / 1000);
return buf;
}
char* Log::currentTimeString(char* buf, size_t bufsize) {
struct timeval tv;
gettimeofday(&tv, NULL);
return timeString(buf, bufsize, tv);
}
const char* Log::setThreadName(std::string&& name) {
folly::setThreadName(name);
threadName->assign(name);
return threadName->value().c_str();
}
const char* Log::getThreadName() {
if (!threadName->hasValue()) {
auto name = folly::getCurrentThreadName();
if (name.hasValue()) {
threadName->assign(name);
} else {
std::stringstream ss;
ss << std::this_thread::get_id();
threadName->assign(ss.str());
}
}
return threadName->value().c_str();
}
void Log::setStdErrLoggingLevel(LogLevel level) {
auto notify = [this]() { doLogToStdErr(); };
switch (level) {
case OFF:
errorSub_.reset();
debugSub_.reset();
return;
case DBG:
if (!debugSub_) {
debugSub_ = debugPub_->subscribe(notify);
}
if (!errorSub_) {
errorSub_ = errorPub_->subscribe(notify);
}
return;
default:
debugSub_.reset();
if (!errorSub_) {
errorSub_ = errorPub_->subscribe(notify);
}
return;
}
}
void Log::doLogToStdErr() {
std::vector<std::shared_ptr<const watchman::Publisher::Item>> items;
{
std::lock_guard<std::mutex> lock(stdErrPrintMutex_);
getPending(items, errorSub_, debugSub_);
}
bool doFatal = false;
bool doAbort = false;
static w_string kFatal("fatal");
static w_string kAbort("abort");
for (auto& item : items) {
auto& log = json_to_w_string(item->payload.get("log"));
ignore_result(::write(STDERR_FILENO, log.data(), log.size()));
auto level = json_to_w_string(item->payload.get("level"));
if (level == kFatal) {
doFatal = true;
} else if (level == kAbort) {
doAbort = true;
}
}
if (doFatal || doAbort) {
log_stack_trace();
if (doAbort) {
abort();
} else {
_exit(1);
}
}
}
#ifdef _WIN32
LONG WINAPI exception_filter(LPEXCEPTION_POINTERS excep) {
std::array<void*, kMaxFrames> array;
size_t size;
char** strings;
size_t i;
char timebuf[64];
size = backtrace_from_exception(excep, array.data(), array.size());
strings = backtrace_symbols(array.data(), size);
write_stderr(
watchman::Log::currentTimeString(timebuf, sizeof(timebuf)),
": [",
watchman::Log::getThreadName(),
"] Unhandled win32 exception code=",
folly::to<std::string>(excep->ExceptionRecord->ExceptionCode),
". Fatal error detected at:\n");
for (i = 0; i < size; i++) {
write_stderr(strings[i], "\n");
}
free(strings);
write_stderr("the stack trace for the exception filter call is:\n");
size = backtrace(array.data(), array.size());
strings = backtrace_symbols(array.data(), size);
for (i = 0; i < size; i++) {
write_stderr(strings[i], "\n");
}
free(strings);
// Terminate the process.
// msvcrt abort() ultimately calls exit(3), so we shortcut that.
// Ideally we'd just exit() or ExitProcess() and be done, but it
// is documented as possible (or even likely!) that deadlock
// is possible, so we use TerminateProcess() to force ourselves
// to terminate.
TerminateProcess(GetCurrentProcess(), 3);
// However, TerminateProcess() is asynchronous and we will continue
// running here. Let's also try exiting normally and see which
// approach wins!
exit(3);
return EXCEPTION_CONTINUE_SEARCH;
}
#endif
} // namespace watchman