#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <thread>
#include <chrono>
#include <ctime>
#include <cstdarg> ///va_start(args, format);
void LogToConsoleAndFile(const std::string& filename, bool includeDate, bool includeThread, const char* format, ...)
{
// 获取当前时间
std::time_t currentTime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::string timeString;
char timeBuffer[26];
struct tm timeinfo;
if (localtime_s(&timeinfo, ¤tTime) == 0)
{
strftime(timeBuffer, sizeof(timeBuffer), "%Y-%m-%d %H:%M:%S", &timeinfo);
timeString = timeBuffer;
}
// 打开文件以追加写入日志
std::ofstream file(filename, std::ios::app);
if (!file.is_open())
{
std::cerr << "无法打开日志文件:" << filename << std::endl;
return;
}
// 格式化日志消息
va_list args;
va_start(args, format);
char logBuffer[256];
vsnprintf(logBuffer, sizeof(logBuffer), format, args);
va_end(args);
// 输出到控制台和文件
if (includeDate)
{
//std::cout << "[" << timeString << "] ";
std::cout << timeString<<" ";
//file << "[" << timeString << "] ";
file << timeString << " ";
}
std::cout << logBuffer << std::endl;
file << logBuffer << std::endl;
// 关闭文件
file.close();
}
#define LOG_TO_CONSOLE_AND_FILE_WITH_DATE_AND_THREAD//时间
//#define LOG_TO_CONSOLE_AND_FILE_WITH_THREAD//去掉时间 或去掉线程的 这几个就为了切换功能的
//#define LOG_TO_CONSOLE_AND_FILE
#ifdef LOG_TO_CONSOLE_AND_FILE_WITH_DATE_AND_THREAD
#define LOG(index, format, ...) LogToConsoleAndFile(std::to_string(index) + windowName + ".txt", true, true, format, __VA_ARGS__)
#elif defined(LOG_TO_CONSOLE_AND_FILE_WITH_THREAD)
#define LOG(index, format, ...) LogToConsoleAndFile(std::to_string(index) + windowName + ".txt", false, true, format, __VA_ARGS__)
#elif defined(LOG_TO_CONSOLE_AND_FILE)
#define LOG(index, format, ...) LogToConsoleAndFile(std::to_string(index) + windowName + ".txt", false, false, format, __VA_ARGS__)
#else
#define LOG(index, format, ...) LogToConsole(format, __VA_ARGS__)
#endif
void ThreadFunction(int index, const std::string& windowName)
{
// 设置窗口名字
std::string threadName = std::to_string(index) + windowName;
// 在不同线程中写入日志
LOG(index, "---%d行------窗口:%s-----------点击羽毛--------", 23, threadName.c_str());
}
int main()
{
std::string windowName = "MyWindow";
int index = 1;
// 在新线程中调用ThreadFunction
std::thread t(ThreadFunction, index, windowName);
t.join();
return 0;
}
console显示时间写入文件,index+窗口名
最新推荐文章于 2024-04-23 10:53:47 发布