在C++中實現異步日志記錄通常使用多線程來實現。以下是一個簡單的示例代碼:
#include <iostream>
#include <fstream>
#include <string>
#include <thread>
#include <queue>
#include <mutex>
#include <condition_variable>
class Logger {
public:
Logger() : isRunning(true) {
outputFile.open("log.txt", std::ios::app);
workerThread = std::thread(&Logger::logWorker, this);
}
~Logger() {
isRunning = false;
workerThread.join();
outputFile.close();
}
void log(const std::string& message) {
std::lock_guard<std::mutex> lock(mutex);
logQueue.push(message);
cv.notify_one();
}
private:
std::ofstream outputFile;
std::queue<std::string> logQueue;
std::mutex mutex;
std::condition_variable cv;
bool isRunning;
std::thread workerThread;
void logWorker() {
while (isRunning) {
std::unique_lock<std::mutex> lock(mutex);
cv.wait(lock, [this] { return !logQueue.empty() || !isRunning; });
while (!logQueue.empty()) {
std::string message = logQueue.front();
logQueue.pop();
outputFile << message << std::endl;
}
}
}
};
int main() {
Logger logger;
logger.log("Hello, World!");
logger.log("This is a log message.");
return 0;
}
在上面的示例中,Logger類包含一個日志隊列logQueue,一個互斥鎖mutex和一個條件變量cv。日志消息通過log()方法添加到隊列中,在logWorker()方法中的工作線程中從隊列中取出消息,并將其寫入日志文件中。當程序結束時,Logger類的析構函數會關閉日志文件并等待工作線程結束。
在主函數中,創建一個Logger實例,并使用log()方法記錄日志消息。由于日志記錄是在后臺線程中進行的,不會阻塞主線程。