温馨提示×

C++程序在Linux上如何进行日志记录

小樊
48
2025-09-25 19:26:22
栏目: 编程语言

在Linux上,C++程序可以使用多种方法进行日志记录。以下是一些常用的日志库和工具:

1. 使用标准库

C++标准库本身并没有提供日志记录功能,但你可以使用文件流(std::ofstream)来写入日志文件。

#include <fstream>
#include <iostream>
#include <string>
#include <ctime>

void logMessage(const std::string& message) {
    std::ofstream logFile("app.log", std::ios::app);
    if (logFile.is_open()) {
        time_t now = time(0);
        char* dt = ctime(&now);
        logFile << "[" << dt << "] " << message << std::endl;
        logFile.close();
    } else {
        std::cerr << "Unable to open log file" << std::endl;
    }
}

int main() {
    logMessage("This is a log message.");
    return 0;
}

2. 使用第三方日志库

a. Boost.Log

Boost.Log是一个功能强大的日志库,提供了丰富的日志记录功能。

#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/sinks/text_file_backend.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/console.hpp>

namespace logging = boost::log;
namespace src = boost::log::sources;
namespace sinks = boost::log::sinks;
namespace expr = boost::log::expressions;

void initLogging() {
    // 添加文件日志后端
    typedef sinks::text_file_backend< sinks::file::rotation_size<10*1024*1024>, sinks::file::time_based_rotation >
        file_backend;
    file_backend backend;
    backend.add_file("app.log");
    backend.auto_flush(true);

    // 添加控制台日志后端
    typedef sinks::synchronous_sink< sinks::text_ostream_backend< sinks::text_ostream_backend::stream_type& > >
        text_sink;
    text_sink sink(std::cout);
    sink.backends.push_back(backend);

    // 设置日志格式
    expr::stream< expr::keyword::tag< "Severity" >, expr::keyword::tag< "Message" > >
        formatter = expr::stream
            << "[" << expr::attr< std::string >("Severity") << "] "
            << expr::attr< std::string >("Message");
    sink.set_formatter(formatter);

    // 添加日志属性
    logging::add_common_attributes();

    // 注册日志记录器
    logging::core::get()->add_sink(sink);
}

int main() {
    initLogging();
    BOOST_LOG_TRIVIAL(info) << "This is an info message.";
    BOOST_LOG_TRIVIAL(warning) << "This is a warning message.";
    BOOST_LOG_TRIVIAL(error) << "This is an error message.";
    return 0;
}

b. spdlog

spdlog是一个非常快速且易于使用的日志库。

#include "spdlog/spdlog.h"
#include "spdlog/sinks/stdout_color_sinks.h"
#include "spdlog/sinks/basic_file_sink.h"

int main() {
    // 创建控制台日志记录器
    auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
    console_sink->set_pattern("[%Y-%m-%d %H:%M:%S] [%l] %v");
    spdlog::register_logger(console_sink);

    // 创建文件日志记录器
    auto file_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>("app.log", true);
    file_sink->set_pattern("[%Y-%m-%d %H:%M:%S] [%l] %v");
    spdlog::register_logger(file_sink);

    // 获取日志记录器
    auto logger = spdlog::get("console");
    logger->info("This is an info message.");
    logger->warn("This is a warning message.");
    logger->error("This is an error message.");

    return 0;
}

3. 使用系统日志

Linux系统提供了syslog服务,你可以使用syslog库来记录日志。

#include <syslog.h>
#include <iostream>
#include <string>

void logMessage(const std::string& message) {
    openlog("myapp", LOG_PID | LOG_CONS, LOG_USER);
    syslog(LOG_INFO, "%s", message.c_str());
    closelog();
}

int main() {
    logMessage("This is a log message.");
    return 0;
}

总结

选择哪种方法取决于你的需求。如果你需要简单的日志记录功能,使用标准库或系统日志可能就足够了。如果你需要更高级的功能(如日志级别、格式化、多线程支持等),那么使用第三方日志库(如Boost.Log或spdlog)会更好。

0