【问题标题】:Obtaining formatted strings from a text_file_backend从 text_file_backend 获取格式化字符串
【发布时间】:2016-04-28 08:13:30
【问题描述】:

我在我的应用程序中使用 boost-log。我想将日志写入文件并通过网络发送记录的字符串(用于复制目的)。

对于文件记录,我使用的是text_file_backend(连同synchronous_sink<text_file_backend>);这很好用,并以某种格式记录到文件信息。我想获得相同格式的字符串,以便能够通过网络发送。

如何从text_file_backend 中挤出它将写入文件的实际字符串?

【问题讨论】:

    标签: c++ logging boost boost-log


    【解决方案1】:

    您可以尝试将multiple stream 添加到backend

    void init_logging()
    {
        boost::shared_ptr< logging::core > core = logging::core::get();
    
        // Create a backend and attach a couple of streams to it
        boost::shared_ptr< sinks::text_ostream_backend > backend =
            boost::make_shared< sinks::text_ostream_backend >();
        backend->add_stream(
            boost::shared_ptr< std::ostream >(&std::clog, boost::null_deleter()));
        backend->add_stream(
            boost::shared_ptr< std::ostream >(new std::ofstream("sample.log")));
    
        /*** Add your network stream here ***/
    
        typedef sinks::synchronous_sink< sinks::text_ostream_backend > sink_t;
        boost::shared_ptr< sink_t > sink(new sink_t(backend));
        core->add_sink(sink);
    }
    

    更新

    坚持text_file_backend,您可以使用void set_close_handler(close_handler_type const &amp; handler) 设置一个回调函数,该函数读取关闭的日志文件并将其发送到您的日志服务器。

    如果您无法忍受延迟,请使用set_open_handler,并启动一个新线程来读取文件。

    最终,您可以继承 text_file_backend 并重载我认为 fontend 调用的 consume 方法。后端API参考this页面

    【讨论】:

    • 这也是我想到的第一件事。但似乎text_file_backend 没有提供add_stream 功能。
    • 不要使用text_file_backend,而是使用text_ostream_backend。还是需要text_file_backend的文件分离(旋转)功能?
    • 是的,我需要文件轮换,因为应用程序应该运行无限长的时间。我已经解决了添加text_ostream_backend 的问题,但我不敢相信没有办法避免这种重复...
    猜你喜欢
    • 1970-01-01
    • 2021-03-13
    • 1970-01-01
    • 2011-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-30
    相关资源
    最近更新 更多