1、示例记录:通过单例模式实现日志记录
2、日志等级:分为三级(INFO、WARNING、ERROR)
3、日志输出:不同等级日志将输出到不同文件
4、日志报错:输出到文本文件,并按照日期生成新的文件
待优化:当前文件日志量大于指定阈值时,再创建新的文件存储日志。
功能实现:
#if 1
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define MAX_PATH 260
// 日志等级枚举
enum class LogLevel
{
INFO,
WARNING,
ERROR
};
class Logger
{
public:
static Logger& getInstance()
{
static Logger instance; // 在首次调用时初始化
return instance;
}
void log(LogLevel level, const std::string& message)
{
checkDate(level); // 检查日期是否变化
// 使用互斥锁保护日志文件写入操作
std::lock_guard<std::mutex> lock(m_write_mutex);
m_current_level = level; // 更新当前日志等级
// 根据日志等级调用不同的输出方法
switch (level)
{
case LogLevel::INFO:
logInfo(message);
break;
case LogLevel::WARNING:
logWarning(message);
break;
case LogLevel::ERROR:
logError(message);
break;
}
}
bool createLogDirectory(const std::string& dirPath)
{
if (directoryExists(dirPath))
{
std::cout << "Directory already exists: " << dirPath << std::endl;
return true;
}
int result = _mkdir(dirPath.c_str());
if (result == 0)
{
std::cout << "Directory created successfully: " << dirPath << std::endl;
return true;
}
else
{
std::cerr << "Failed to create directory: " << dirPath << std::endl;
return false;
}
}
void setLogPath(const std::string& path)
{
m_dir_path = path;
}
std::string getLogPath() const
{
return m_dir_path;
}
private:
Logger()
{
m_dir_path = getCurrentWorkingDirectory();
m_current_level = LogLevel::INFO;
createLogFile(m_current_level);
}
~Logger()
{
if (m_file.is_open())
{
m_file.close(); // 关闭日志文件
}
}
Logger(Logger const&) = delete; // 禁止拷贝构造
void operator=(Logger const&) = delete; // 禁止赋值操作符重载
// 输出不同等级的日志
void logInfo(const std::string& message)
{
std::cout << "[INFO] " << getCurrentTimestamp() << " " << message << std::endl;
if (m_file.is_open())
{
m_file << "[INFO] " << getCurrentTimestamp() << " " << message << std::endl;
}
}
void logWarning(const std::string& message)
{
std::cout << "[WARNING] " << getCurrentTimestamp() << " " << message << std::endl;
if (m_file.is_open())
{
m_file << "[WARNING] " << getCurrentTimestamp() << " " << message << std::endl;
}
}
void logError(const std::string& message)
{
std::cout << "[ERROR] " << getCurrentTimestamp() << " " << message << std::endl;
if (m_file.is_open())
{
m_file << "[ERROR] " << getCurrentTimestamp() << " " << message << std::endl;
}
}
bool fileExists(const std::string& filePath) const
{
std::ifstream ifs(filePath);
return ifs.good();
}
// 创建新的日志文件
void createLogFile(LogLevel level)
{
std::lock_guard<std::mutex> lock(m_create_mutex);
if (m_file.is_open())
{
m_file.close(); // 关闭之前的日志文件
}
m_file.open(generateLogFileName(level), std::ios_base::app); // 打开日志文件,追加写入
}
// 根据日志等级生成新的日志文件名
std::string generateLogFileName(LogLevel level)
{
std::stringstream ss;
ss << m_dir_path << "\\" << "log_";
switch (level)
{
case LogLevel::INFO:
ss << "info_";
break;
case LogLevel::WARNING:
ss << "warning_";
break;
case LogLevel::ERROR:
ss << "error_";
break;
default:
ss << "info_";
break;
}
auto now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::tm* currentTime = std::localtime(&now);
ss << (currentTime->tm_year + 1900) << "-" << (currentTime->tm_mon + 1) << "-" << currentTime->tm_mday;
ss << ".log";
return ss.str();
}
// 检查当前日期是否变化,如果是则创建新的日志文件
void checkDate(LogLevel level)
{
bool exist = fileExists(generateLogFileName(level));
createLogFile(level);
//auto now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
//if (std::localtime(&now)->tm_mday != m_last_log_day || !exist)
//{
// m_last_log_day = std::localtime(&now)->tm_mday;
// createLogFile(level);
//}
}
// 检查当前日志文件大小,如果超过阈值则创建新的日志文件
//bool checkFileSize(LogLevel level)
//{
// if (m_file.is_open())
// {
// std::streampos currentPos = m_file.tellp(); // 当前文件位置
// m_file.seekp(0, std::ios::end);
// std::streampos fileSize = m_file.tellp(); // 当前文件大小
// m_file.seekp(currentPos, std::ios::beg); // 恢复文件位置
// if (fileSize > m_max_file_size)
// {
// m_file.close();
// }
// }
//}
std::string getCurrentTimestamp() const
{
auto now = std::chrono::system_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
// 将毫秒级时间戳转换为time_t类型
time_t t = ms / 1000;
// 使用gmtime函数将time_t类型转换为tm结构体(协调世界时)
struct tm* tm_struct = std::gmtime(&t);
char buffer[80];
// 使用strftime函数将tm结构体转换为日期格式
std::strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", tm_struct);
int get_ms = ms % 1000;
char format[100] = { 0 };
sprintf_s(format, "%s %03d ", buffer, get_ms);
// 将毫秒级时间戳添加到日期格式后面
//std::string dateTime = buffer + std::string(" ") + std::to_string(ms % 1000) + std::string(" ");
return std::string(format);
}
std::string getCurrentWorkingDirectory() const
{
char temp[MAX_PATH];
if (_getcwd(temp, MAX_PATH) != NULL)
{
return std::string(temp);
}
else
{
return std::string("");
}
}
bool directoryExists(const std::string& dirPath) const
{
struct stat info;
if (stat(dirPath.c_str(), &info) != 0)
{
return false; // 目录不存在
}
return (info.st_mode & S_IFDIR) != 0; // 判断是否为目录
}
private:
std::ofstream m_file; // 日志文件流
const std::streampos m_max_file_size = 1024 * 1024; // 文件大小阈值,1MB
long long m_last_log_day = -1; // 上次记录的日期
std::mutex m_write_mutex; // 互斥锁
std::mutex m_create_mutex; // 互斥锁
LogLevel m_current_level;
std::string m_dir_path;
};
#endif
测试实现:
int main()
{
Logger& logger = Logger::getInstance();
logger.createLogDirectory("C:\\test_log");
logger.createLogDirectory("C:\\test_log\\log");
logger.setLogPath("C:\\test_log\\log");
for (int i = 0; i < 10; ++i)
{
logger.log(LogLevel::INFO, "This is an information message.");
std::this_thread::sleep_for(std::chrono::milliseconds(200));
logger.log(LogLevel::WARNING, "This is an warning message.");
std::this_thread::sleep_for(std::chrono::milliseconds(200));
logger.log(LogLevel::ERROR, "This is an error message.");
std::this_thread::sleep_for(std::chrono::milliseconds(200));
}
return 0;
}