game2006/server/gameserver/tracemgr.cc
aozhiwei 58f14b7107 1
2022-10-01 08:06:20 +08:00

74 lines
1.4 KiB
C++

#include "precompile.h"
#include <execinfo.h>
#include "tracemgr.h"
#ifdef DEBUG
#if __GNUC__ > 4
static void ErrorCallback(void *data, const char *msg, int errnum)
{
A8_ABORT();
}
#endif
void TraceMgr::Init(const std::string& filename)
{
filename_ = filename;
#if __GNUC__ > 4
state_ = backtrace_create_state(filename_.c_str(),
0,
ErrorCallback,
nullptr);
if (!state_) {
A8_ABORT();
}
#endif
log_file_ = fopen("backtrace.log", "w");
if (!log_file_) {
A8_ABORT();
}
}
void TraceMgr::UnInit()
{
if (log_file_) {
fclose(log_file_);
log_file_ = nullptr;
}
}
void TraceMgr::Trace(const std::string& hint)
{
#if __GNUC__ > 4
fputs(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n", log_file_);
fputs(hint.c_str(), log_file_);
backtrace_print(state_, 0, log_file_);
fputs("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n", log_file_);
#endif
}
std::string TraceMgr::GetBackTrace()
{
const int BT_BUF_SIZE = 1024 * 10;
std::string data;
void *buffer[BT_BUF_SIZE];
char **strings = nullptr;
int nptrs = backtrace(buffer, BT_BUF_SIZE);
strings = backtrace_symbols(buffer, nptrs);
if (strings) {
for (int i = 0; i < nptrs; i++) {
data += strings[i];
data += "\n";
}
free(strings);
}
return data;
}
#endif