21

C++ アプリケーションで Boost(1.55.0) Logging を使用しています。この形式のログを生成できました

[2014-Jul-15 10:47:26.137959]: <debug>  A regular message

ログが生成されるソースファイル名と行番号を追加できるようにしたい。

[2014-Jul-15 10:47:26.137959]: <debug> [filename:line_no] A regular message

例:

[2014-Jul-15 10:47:26.137959]: <debug> [helloworld.cpp : 12] A regular message

ソースコード:

#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/common_attributes.hpp>
#include <boost/log/sources/severity_logger.hpp>
#include <boost/log/sources/record_ostream.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/support/date_time.hpp>
#include <boost/log/attributes/attribute.hpp>
#include <boost/log/attributes/attribute_cast.hpp>
#include <boost/log/attributes/attribute_value.hpp>
#include <boost/make_shared.hpp>
#include <boost/property_tree/ptree.hpp>

namespace logging = boost::log;
namespace src = boost::log::sources;
namespace sinks = boost::log::sinks;
namespace keywords = boost::log::keywords;

void init()
{
    logging::add_file_log
    (
        keywords::file_name = "sample_%N.log",                                        /*< file name pattern >*/
        keywords::rotation_size = 10*1024*1204,                                 /*< rotate files every 10 MiB... >*/
        keywords::time_based_rotation = sinks::file::rotation_at_time_point(0, 0, 0), /*< ...or at midnight >*/
        keywords::format =
        (
            boost::log::expressions::stream
                << boost::log::expressions::format_date_time< boost::posix_time::ptime >("TimeStamp", "%Y-%m-%d_%H:%M:%S.%f")
                << ": <" << boost::log::trivial::severity << "> "
                << boost::log::expressions::smessage
        )
    );
}

int main(int, char*[])
{
    init();
    logging::add_common_attributes();

    using namespace logging::trivial;
    src::severity_logger< severity_level > lg;

    BOOST_LOG_SEV(lg, debug) << "A regular message";
    return 0;
}
4

4 に答える 4

1

定義

namespace attrs = boost::logging::attributes;
namespace expr = boost::logging::expressions;

追加

<< expr::format_named_scope("Scope", keywords::format = "[%f:%l]")

あなたのkeywords::format = (...)中にinit

それから加えて

logging::core::get()->add_global_attribute("Scope", attrs::named_scope());

アフターadd_common_attributes()インmain

BOOST_LOG_SEV次に、行の直前にBOOST_LOG_NAMED_SCOPE("whatever").

BOOST_LOG_NAMED_SCOPE("whatever")「whatever」という名前の「スコープ」を作成します。スコープは、スコープ名、ファイル、およびスコープが定義された行を含む未使用の変数によって実装されます。

このformat_named_scope行は、ログ行でスコープをフォーマットする方法を指定します。%f はファイル、%l は行、%n はスコープ名です。

ログ レコードに表示されるファイル行は、マクロBOOST_LOG_NAMED_SCOPEの行ではなく、マクロが表示される行であることに注意してくださいBOOST_LOG_SEV

を使用せずにファイルと行を記録する簡単な方法を知りませんBOOST_LOG_NAMED_SCOPE

于 2014-08-11T22:04:57.177 に答える