webserver/headers/hlog.hpp
2025-04-28 20:47:53 +08:00

94 lines
1.6 KiB
C++

#ifndef HLOG_H
#define HLOG_H
#include <string>
#include <mutex>
#include <memory>
#include <htime.hpp>
#include <cstdarg>
#define LOG hlog::getLogger()->WRITE_LOG
enum class hlog_level
{
HLOG_INFO,
HLOG_WARN,
HLOG_ERR,
HLOG_CRIT
};
namespace
{
std::string hlog_level_to_string(const hlog_level &level)
{
switch (level)
{
case hlog_level::HLOG_INFO:
return "INFO";
case hlog_level::HLOG_WARN:
return "WARNING";
case hlog_level::HLOG_ERR:
return "ERROR";
case hlog_level::HLOG_CRIT:
return "CRITICAL";
default:
return "UNKNOWN";
}
}
}
class hlog
{
private:
static hlog *global_hloger;
static std::mutex mtx;
static Htime htimer;
hlog()
{
}
public:
static hlog *getLogger()
{
if (global_hloger == nullptr)
{
std::lock_guard<std::mutex> lock(mtx);
if (global_hloger == nullptr)
{
global_hloger = new hlog();
}
}
return global_hloger;
}
void WRITE_LOG(hlog_level level, const char *fmt, ...)
{
printf("[%s]:[%-10s]--[", htimer.get_local_time_now().c_str(), hlog_level_to_string(level).c_str());
va_list ap;
va_start(ap, fmt);
vprintf(fmt, ap);
va_end(ap);
printf("]\n");
}
static void destroy()
{
if (global_hloger != nullptr)
{
delete global_hloger;
global_hloger = nullptr;
}
}
};
hlog *hlog::global_hloger = nullptr;
std::mutex hlog::mtx;
Htime hlog::htimer;
#endif