| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- #define _CRT_SECURE_NO_WARNINGS
- #include "Logger.h"
- #include <iostream>
- #include <ctime>
- #include <windows.h>
- std::unique_ptr<Logger> Logger::instance_ = nullptr;
- std::mutex Logger::mutex_;
- Logger::Logger(const std::string& log_file_path) : log_file_path_(log_file_path) {
- // 获取可执行文件所在目录
- char buffer[MAX_PATH];
- GetModuleFileNameA(NULL, buffer, MAX_PATH);
- std::string::size_type pos = std::string(buffer).find_last_of("\\");
- std::string exe_path = std::string(buffer).substr(0, pos);
-
- // 构建完整的日志文件路径
- std::string full_log_path = exe_path + "\\" + log_file_path;
-
- log_file_.open(full_log_path, std::ios::app);
- if (!log_file_.is_open()) {
- std::cerr << "Failed to open log file: " << full_log_path << std::endl;
- }
- }
- Logger::~Logger() {
- if (log_file_.is_open()) {
- log_file_.close();
- }
- }
- Logger* Logger::GetInstance(const std::string& log_file_path) {
- std::lock_guard<std::mutex> lock(mutex_);
- if (instance_ == nullptr) {
- std::string path = log_file_path.empty() ? "CommModifyService.log" : log_file_path;
- instance_ = std::unique_ptr<Logger>(new Logger(path));
- }
- return instance_.get();
- }
- void Logger::Log(LogLevel level, const std::string& message) {
- return;
- std::lock_guard<std::mutex> lock(file_mutex_);
-
- // 获取当前时间
- auto now = std::time(nullptr);
- auto tm = *std::localtime(&now);
-
- // 格式化时间字符串
- char time_buffer[100];
- std::strftime(time_buffer, sizeof(time_buffer), "%Y-%m-%d %H:%M:%S", &tm);
-
- // 获取日志级别字符串
- std::string level_str;
- switch (level) {
- case LogLevel::LOG_LEVEL_INFO: level_str = "INFO"; break;
- case LogLevel::LOG_LEVEL_WARNING: level_str = "WARNING"; break;
- case LogLevel::LOG_LEVEL_ERROR: level_str = "ERROR"; break;
- case LogLevel::LOG_LEVEL_DEBUG: level_str = "DEBUG"; break;
- }
-
- // 构建日志消息
- std::string log_message = "[" + std::string(time_buffer) + "] [" + level_str + "] " + message;
-
- // 写入文件
- if (log_file_.is_open()) {
- log_file_ << log_message << std::endl;
- log_file_.flush();
- }
-
- // 输出到控制台
- std::cout << log_message << std::endl;
- }
- void Logger::LogInfo(const std::string& message) {
- Log(LogLevel::LOG_LEVEL_INFO, message);
- }
- void Logger::LogWarning(const std::string& message) {
- Log(LogLevel::LOG_LEVEL_WARNING, message);
- }
- void Logger::LogError(const std::string& message) {
- Log(LogLevel::LOG_LEVEL_ERROR, message);
- }
- void Logger::LogDebug(const std::string& message) {
- Log(LogLevel::LOG_LEVEL_DEBUG, message);
- }
|