Files
dl_old/dl/io/dl_log.cpp
T

404 lines
9.4 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include "dl_log.h"
#include <cassert>
#include <fstream>
#if (DL_PLATFORM == DL_PLATFORM_WIN32)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <vld.h>
#endif
#include "system/dl_time.h"
#include "base/dl_range_erase.h"
#include "memory/dl_code_cvt.h"
#include "base/dl_string.h"
#include "dl_file.h"
#include "math/dl_math.h"
namespace dl
{
LogSystem* g_log = nullptr;
std::ofstream g_logOfs;
void Output(std::string_view str)
{
printf("%s", str.data());
#if (DL_PLATFORM == DL_PLATFORM_WIN32)
OutputDebugStringW(CodeCvt::Utf8ToWideChar(str).c_str());
#endif
std::mutex& m = g_log->GetMutex();
m.lock();
if(g_logOfs.is_open())
g_logOfs.write(str.data(), str.size());
m.unlock();
}
void OutputEndl()
{
printf("\n");
#if (DL_PLATFORM == DL_PLATFORM_WIN32)
OutputDebugStringW(L"\n");
#endif
std::mutex& m = g_log->GetMutex();
m.lock();
if (g_logOfs.is_open())
g_logOfs << '\n';
m.unlock();
}
#if (DL_PLATFORM == DL_PLATFORM_WIN32)
HANDLE g_log_handle = INVALID_HANDLE_VALUE;
/**
* @brief 根据日志等级,设置控制台颜色
*/
void SetLevelColor(LogSystem::Level level)
{
switch (level)
{
case LogSystem::Level::PAUSE:
SetConsoleTextAttribute(g_log_handle,
FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE |
FOREGROUND_INTENSITY);
break;
case LogSystem::Level::TEST:
SetConsoleTextAttribute(g_log_handle,
FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE |
BACKGROUND_BLUE |
FOREGROUND_INTENSITY);
break;
case LogSystem::Level::INFO:
SetConsoleTextAttribute(g_log_handle,
BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE |
BACKGROUND_INTENSITY);
break;
case LogSystem::Level::MSG:
SetConsoleTextAttribute(g_log_handle,
FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE |
BACKGROUND_RED | BACKGROUND_BLUE |
FOREGROUND_INTENSITY);
break;
case LogSystem::Level::NOTICE:
SetConsoleTextAttribute(g_log_handle,
BACKGROUND_GREEN |
BACKGROUND_INTENSITY);
break;
case LogSystem::Level::WARN:
SetConsoleTextAttribute(g_log_handle,
FOREGROUND_GREEN | FOREGROUND_RED |
BACKGROUND_GREEN | BACKGROUND_RED |
FOREGROUND_INTENSITY);
break;
case LogSystem::Level::ERR:
SetConsoleTextAttribute(g_log_handle,
FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE |
BACKGROUND_RED);
break;
case LogSystem::Level::DAMAGE:
SetConsoleTextAttribute(g_log_handle,
BACKGROUND_RED |
BACKGROUND_INTENSITY);
break;
}
}
/**
* @brief 设置控制台 时间戳颜色
*/
void SetColorTime()
{
SetConsoleTextAttribute(g_log_handle,
BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE |
BACKGROUND_INTENSITY |
FOREGROUND_INTENSITY);
}
/**
* @brief 设置控制台空格颜色
*/
void SetColorBlank()
{
SetColorTime();
//SetConsoleTextAttribute(g_log_handle,
// FOREGROUND_INTENSITY);
// //BACKGROUND_INTENSITY);
}
void log_imp(std::string_view str, const std::source_location location)
{
const LogSystem::Setting& setting = g_log->GetSetting();
std::mutex& m = g_log->GetMutex();
// 打开日志文件
std::string str_path = g_log->GetLogFile();
if (!str_path.empty())
{
m.lock();
g_logOfs = File::Set(str_path, false, true);
if (!g_logOfs.is_open())
{
log_easy(fmt::format("日志文件打开(写入)失败:{}", str_path));
}
m.unlock();
}
// 源码位置 vs双击定位 需要输出到最前面
if (setting._bSourceLocation)
{
SetColorTime();
// 此种格式才能在vs里跳转
std::string s = fmt::format("{}({},{}):",
String::CvtPathSeparator(location.file_name()),
location.line(), location.column());
Output(fmt::format("{:.<48}", s));
}
// 时间戳
if (setting._bTimeStamp)
{
SetColorTime();
Output(fmt::format("|{}", Time::TimeStamp2String(time(0))));
}
// 函数名
std::string s1 = location.function_name();
{
using namespace std::literals;
if (Erase::TailFromLast(s1, '('))
s1.pop_back();
Erase::AllSub(s1, "class "s);
Erase::AllSub(s1, "void"s);
Erase::AllSub(s1, "__cdecl"s);
Erase::AllSub(s1, "::<lambda_1>::operator ()"s);
//Erase::Range(",std::allocator<", ">")
}
size_t remain_size = Math::SubU(96_zu, s1.size());
// 等级、内容
SetLevelColor(setting._level);
bool short_str = str.size() < remain_size;
if (short_str)
{
for (auto& iter : str)
{
if (iter == '\n')
{
short_str = false;
break;
}
}
}
std::string s;
s += fmt::format("|{:<7}", LogSystem::Level2String(setting._level));
if(short_str)
s += fmt::format("|{:<48}", str);
else
s += fmt::format("|{:.^48}", "");
// 函数名
if (short_str)
{
size_t more_size = Math::SubU(str.size(), 48_zu);
size_t blank_size = Math::SubU(48_zu, more_size + s1.size());
std::string str_bland;
str_bland.resize(blank_size, ' ');
s += fmt::format("|{}{}", str_bland, s1);
}
else
s += fmt::format("|{:>48}", s1);
// 长字符串单独输出到一行
if (!short_str)
s += fmt::format("\n\n{:<48}\n", str);
Output(s);
SetColorBlank();
OutputEndl();
// 堆栈信息
if (setting._bStackTrace)
{
Output(std::to_string(std::stacktrace::current()));
OutputEndl();
}
// 关闭日志暂用
if (!str_path.empty())
g_logOfs.close();
if (g_log->IsLevelMsgBox(setting._level))
{
#if (DL_PLATFORM == DL_PLATFORM_WIN32)
std::string title = fmt::format("{}({}) {} {}",
location.file_name(), location.line(),
Time::TimeStamp2String(time(0)), LogSystem::Level2String(setting._level));
int ret = MessageBoxW(NULL, CodeCvt::Utf8ToWideChar(str + "\n\n" + std::to_string(std::stacktrace::current())).c_str(),
CodeCvt::Utf8ToWideChar(title).c_str(), MB_ABORTRETRYIGNORE | MB_ICONERROR | MB_DEFBUTTON3);
if (ret == IDABORT)
exit(1);
else if (ret == IDRETRY)
__debugbreak();
else if (ret == IDIGNORE)
;
else
assert(0);
#endif
}
else if (setting._level == LogSystem::Level::PAUSE)
{
#if (DL_PLATFORM == DL_PLATFORM_WIN32)
std::wstring str_log = CodeCvt::Utf8ToWideChar(str);
__debugbreak();
#endif
}
}
#define DL_LOG_OUTPUT(level)\
if (g_log->IsLevelLimit(level))\
return;\
g_log->PushLevel(level);\
log_imp(str, location);\
g_log->Pop()
void log_notice0(std::string_view str, const std::source_location location /*= std::source_location::current()*/)
{
DL_LOG_OUTPUT(LogSystem::Level::NOTICE);
}
void log_warn0(std::string_view str, const std::source_location location /*= std::source_location::current()*/)
{
DL_LOG_OUTPUT(LogSystem::Level::WARN);
}
void log_err0(std::string_view str, const std::source_location location /*= std::source_location::current()*/)
{
DL_LOG_OUTPUT(LogSystem::Level::ERR);
}
void log_damage0(std::string_view str, const std::source_location location /*= std::source_location::current()*/)
{
DL_LOG_OUTPUT(LogSystem::Level::DAMAGE);
}
void log_pause0(std::string_view str, const std::source_location location /*= std::source_location::current()*/)
{
DL_LOG_OUTPUT(LogSystem::Level::PAUSE);
}
void log_test0(std::string_view str, const std::source_location location /*= std::source_location::current()*/)
{
DL_LOG_OUTPUT(LogSystem::Level::TEST);
}
void log_info0(std::string_view str, const std::source_location location /*= std::source_location::current()*/)
{
DL_LOG_OUTPUT(LogSystem::Level::INFO);
}
void log_msg0(std::string_view str, const std::source_location location /*= std::source_location::current()*/)
{
DL_LOG_OUTPUT(LogSystem::Level::MSG);
}
void log_err0(const std::exception& e, const std::source_location location /*= std::source_location::current()*/)
{
if (g_log->IsLevelLimit(LogSystem::Level::ERR))
return;
g_log->PushLevel(LogSystem::Level::ERR);
log_imp(fmt::format("捕获到C++异常:{}", CodeCvt::MultiByteToUtf8(e.what())), location);
g_log->Pop();
}
void log_err0(const std::system_error& e, const std::source_location location /*= std::source_location::current()*/)
{
if (g_log->IsLevelLimit(LogSystem::Level::ERR))
return;
g_log->PushLevel(LogSystem::Level::ERR);
log_imp(fmt::format("捕获到系统异常[{}]:{}", e.code().value(), CodeCvt::MultiByteToUtf8(e.what())), location);
g_log->Pop();
}
void log(std::string_view str, const std::source_location location /*= std::source_location::current()*/)
{
if (g_log->IsLevelLimit(g_log->GetSetting()._level))
return;
log_imp(str, location);
}
#endif
#if (DL_PLATFORM == DL_PLATFORM_LINUX)
void log(std::string_view str)
{
std::cout << str << std::endl;
}
void log_err0(const std::exception& e)
{
if (g_log->IsLevelLimit(LogSystem::Level::ERR))
return;
g_log->PushLevel(LogSystem::Level::ERR);
log("捕获到C++异常:" + CodeCvt::MultiByteToUtf8(e.what()));
g_log->Pop();
}
#endif
#if (DL_PLATFORM == DL_PLATFORM_ANDROID)
#include <android/log.h>
void log(std::string_view s)
{
int prio = ANDROID_LOG_INFO;
const char* tag = "TS";
const char* fmt = "%s";
const char* str = s.data();
__android_log_print(prio, tag, fmt, str);
// std::cout << str << std::endl;
}
void log_err0(const std::exception& e)
{
if (g_log->IsLevelLimit(LogSystem::Level::ERR))
return;
g_log->PushLevel(LogSystem::Level::ERR);
log("捕获到C++异常:" + CodeCvt::MultiByteToUtf8(e.what()));
g_log->Pop();
}
#endif
LogSystem::LogSystem() :
_levelMsgBox{ Level::ERR }
{
_stackSetting.push({});
_stackLevel.push(Level::PAUSE);
#if (DL_PLATFORM == DL_PLATFORM_WIN32)
g_log_handle = GetStdHandle(STD_OUTPUT_HANDLE);
#endif
}
void LogSystem::SetLogFile(std::string_view path, std::string_view name /*= {}*/)
{
_logFile = std::string{ path };
if (name.empty())
{
_logFile += Time::ExTimeStamp2StringLog();
_logFile += ".txt";
}
else
_logFile += name;
File::CreateFolder(File::GetFilePath(_logFile));
}
std::string LogSystem::_logFile;
}