Ai
1 Star 0 Fork 0

lsnmjp/code of cpp Linux 算法

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
Log.hpp 5.98 KB
一键复制 编辑 原始数据 按行查看 历史
lsnmjp 提交于 2025-06-19 18:25 +08:00 . final UDP demo code
#pragma once
#include <iostream>
#include <string>
#include <memory>
#include <unistd.h>
#include <ctime>
#include <filesystem> //c++17
#include <fstream>
#include "Mutex.hpp"
namespace LogModule
{
using namespace LockMoudle;
namespace fs = std::filesystem;
enum class LogLevel
{
DEBUG = 1,
INFO,
WARN,
ERROR,
FATAL
};
std::string LeveltoString(LogLevel level)
{
switch (level)
{
case (LogLevel::DEBUG):
return "DEBUG";
case (LogLevel::INFO):
return "INFO";
case (LogLevel::WARN):
return "WARN";
case (LogLevel::ERROR):
return "ERROR";
case (LogLevel::FATAL):
return "FATAL";
default:
return "None";
}
}
std::string DefaultLogName = "log.txt";
std::string DefaultLogPath = "./log/";
std::string GetCurrentTime()
{
time_t time_stamp = ::time(nullptr);//time_stamp,即时间戳
struct tm curr;
localtime_r(&time_stamp, &curr);
char buffer[512];
// 2025-05-20 02:37:59
snprintf(buffer, sizeof(buffer), "%4d-%02d-%02d %02d:%02d:%02d",
curr.tm_year + 1900,
curr.tm_mon + 1,
curr.tm_mday,
curr.tm_hour,
curr.tm_min,
curr.tm_sec);
return buffer;
}
// 顶级刷新模式
class LogStrategy
{
public:
LogStrategy()
{
}
virtual void SyncLog(const std::string &message) = 0; // 具体的Synchronization要依靠基类自己实现!
virtual ~LogStrategy() = default; // 基类的析构函数必须设计成虚函数!
private:
};
// 控制台刷新模式
class ConsoleStrategy : public LogStrategy
{
public:
ConsoleStrategy() {};
~ConsoleStrategy() {}; // 尽管什么都不做,但是必须实现一份
void SyncLog(const std::string &message)
{
MutexGuard lockguard(_mutex);
std::cout << message << std::endl;
};
private:
Mutex _mutex;
};
// 文件系统刷新模式
class FileStrategy : public LogStrategy
{
public:
FileStrategy(std::string log_name = DefaultLogName, std::string log_path = DefaultLogPath)
: _log_name(log_name), _log_path(log_path)
{
// 确认logpath是存在的
MutexGuard lock(_mutex);
if (fs::exists(_log_path))
{
return;
}
try
{
fs::create_directories(_log_path);
}
catch (const fs::filesystem_error &e)
{
std::cerr << e.what() << '\n';
}
}
~FileStrategy() {}
void SyncLog(const std::string &message)
{
std::string _file = _log_path + _log_name; // log/log.txt
std::ofstream out(_file, std::ios::app);//之所以不用确认log.txt一定是打开的,是因为Ofstream的标准行为会打开一个没有打开的文件
if (!out.is_open()) // out的接口明显就C++的味道
{
//高概率不会走到这里
return;
}
out << message << std::endl;
out.close();
}
private:
Mutex _mutex;
std::string _log_name;
std::string _log_path;
};
class Logger
{
public:
//默认是ConsoleStrategy
Logger()
{
_strategy = std::make_shared<ConsoleStrategy>();
}
void EnableConsole()
{
_strategy = std::make_shared<ConsoleStrategy>();
}
void EnableFile()
{
_strategy = std::make_shared<FileStrategy>();
}
~Logger()
{
}
class LogMessage
{
public:
LogMessage(LogLevel level, const std::string &filename, int line,Logger& logger)
: _pid(getpid())
, _level(level)
, _filename(filename)
, _line(line)
, _curr_time(GetCurrentTime())
, _logger(logger)
{
//[2024-08-04 12:27:03] [DEBUG] [202938] [main.cc][16] - hello world
std::stringstream _all_buffer;
_all_buffer<<"["<<_curr_time<<"] "
<<"["<<LeveltoString(_level)<<"] "
<<"["<<_pid<<"] "
<<"["<<_filename<<"] "
<<"["<<line<<"] - ";
_all_log_info = _all_buffer.str();
}
template<typename T>
LogMessage& operator<<(const T& info)
{
std::stringstream _buffer;
_buffer<<info;
_all_log_info+=_buffer.str();
return *this;
}
~LogMessage()
{
if(_logger._strategy)
{
_logger._strategy->SyncLog(_all_log_info);
}
}
private:
std::string _curr_time; // 日志时间
LogLevel _level; // 日志等级
std::string _filename; // 文件名
int _line; // 行数
pid_t _pid; // 进程Pid
Logger& _logger; //为了在析构中调用对应的日志策略!
std::string _all_log_info; // 整体构建好的信息
};
LogMessage operator()(LogLevel level, const std::string &filename, int line)
{
return LogMessage(level,filename,line,*this);
}
private:
std::shared_ptr<LogStrategy> _strategy;
};
Logger logger;//used like logger(DEBUG,lig.txt,3);
#define LOG(level) logger(level,__FILE__,__LINE__) //used like LOG(DEBUG)
#define ENABLE_CONSOLE_LOG logger.EnableConsole()
#define ENABLE_FILE_LOG logger.EnableFile()
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/lsnmjp/code-of-cpp-linux-algorithm.git
git@gitee.com:lsnmjp/code-of-cpp-linux-algorithm.git
lsnmjp
code-of-cpp-linux-algorithm
code of cpp Linux 算法
master

搜索帮助