在Linux下使用C++实现高效的日志记录,可以采用以下几种方法:
#include <iostream>
#include <fstream>
void log(const std::string& message) {
std::ofstream log_file("log.txt", std::ios_base::app);
if (log_file.is_open()) {
log_file << message << std::endl;
log_file.close();
}
}
以spdlog为例,你可以这样使用:
#include "spdlog/spdlog.h"
#include "spdlog/sinks/basic_file_sink.h"
int main() {
auto logger = spdlog::basic_logger_mt("logger", "logs/basic-log.txt");
spdlog::set_level(spdlog::level::debug); // 设置日志级别
logger->info("Welcome to spdlog!");
logger->error("Some error message with arg: {}", 1);
return 0;
}
以下是一个简单的异步日志记录示例:
#include <iostream>
#include <fstream>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <thread>
class AsyncLogger {
public:
AsyncLogger(const std::string& file_name) : stop(false) {
log_thread = std::thread(&AsyncLogger::process_logs, this);
}
~AsyncLogger() {
{
std::unique_lock<std::mutex> lock(mtx);
stop = true;
}
cv.notify_all();
log_thread.join();
}
void log(const std::string& message) {
std::unique_lock<std::mutex> lock(mtx);
log_queue.push(message);
cv.notify_one();
}
private:
void process_logs() {
std::ofstream log_file("log.txt", std::ios_base::app);
while (true) {
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, [this] { return !log_queue.empty() || stop; });
if (stop && log_queue.empty()) {
break;
}
auto message = log_queue.front();
log_queue.pop();
lock.unlock();
log_file << message << std::endl;
}
}
std::thread log_thread;
std::mutex mtx;
std::condition_variable cv;
std::queue<std::string> log_queue;
bool stop;
};
int main() {
AsyncLogger logger("log.txt");
for (int i = 0; i < 10; ++i) {
logger.log("Log message " + std::to_string(i));
}
return 0;
}
这个示例中,我们创建了一个AsyncLogger类,它使用一个单独的线程来处理日志记录。我们将日志消息放入一个队列中,然后由日志线程异步地将它们写入文件。这样可以避免在主线程中进行耗时的磁盘操作,从而提高程序的性能。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>