1、可以选择显示时间、日期时间、不显示时间和日期
2、要养成使用define简化代码和当开关的习惯
#include <iostream>
#include <fstream>
#include <chrono>
#include <ctime>
#include <cstdarg>
#include <sstream>
#include <thread>#define LOG_TO_CONSOLE_AND_FILE
#ifdef LOG_TO_CONSOLE_AND_FILE_WITH_DATE
#define LOG(format, ...) LogToConsoleAndFile(std::to_string(index) + windowName + ".txt", true, format, __VA_ARGS__)
#elif defined(LOG_TO_CONSOLE_AND_FILE)
#define LOG(format, ...) LogToConsoleAndFile(std::to_string(index) + windowName + ".txt", false, format, __VA_ARGS__)
#else
#define LOG(format, ...) LogToConsole(format, __VA_ARGS__)
#endifvoid LogToConsole(const char* format, ...)
{va_list args;va_start(args, format);vprintf(format, args);va_end(args);
}void LogToConsoleAndFile(const std::string& filename, bool includeDate, const char* format, ...)
{std::ofstream file(filename, std::ios::app);if (!file.is_open()){std::cerr << "无法打开日志文件:" << filename << std::endl;return;}auto now = std::chrono::system_clock::now();std::time_t currentTime = std::chrono::system_clock::to_time_t(now);std::tm timeInfo;
#ifdef _WIN32localtime_s(&timeInfo, ¤tTime);
#elselocaltime_r(¤tTime, &timeInfo);
#endifchar timeBuffer[128];if (includeDate){std::strftime(timeBuffer, sizeof(timeBuffer), "%Y-%m-%d %H:%M:%S", &timeInfo);}else{std::strftime(timeBuffer, sizeof(timeBuffer), "%H:%M:%S", &timeInfo);}va_list args;va_start(args, format);char buffer[256];vsnprintf(buffer, sizeof(buffer), format, args);va_end(args);std::printf("%s %s", timeBuffer, buffer);file << timeBuffer << " " << buffer;
}void ThreadFunction(int index, const std::string& windowName)
{std::string filename = std::to_string(index) + windowName;long x1{3243}, y1{423}, x2{42}, y2{-55};LOG("---%d行------窗口:%s-----------点击羽毛,坐标%d,%d,%d,%d--------\n", 23, filename.c_str(), x1, y1, x2, y2);
}int main()
{std::thread thread1(ThreadFunction, 0, "窗口1");std::thread thread2(ThreadFunction, 100, "窗口2");thread1.join();thread2.join();return 0;
}