【问题标题】:boost log to print source code file name and line numberboost log 打印源代码文件名和行号
【发布时间】:2014-09-05 04:15:20
【问题描述】:

我在我的 C++ 应用程序中使用 Boost(1.55.0) 登录。 我已经能够生成这种格式的日志

[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;
}

【问题讨论】:

标签: c++ boost boost-log boost-logging


【解决方案1】:

正如Horus 所指出的,您可以使用属性来记录文件和行号。但是最好避免使用多语句宏,以避免出现这样的表达式问题:

if (something)
   LOG_FILE_LINE(debug) << "It's true"; // Only the first statement is conditional!

您可以更好地创建一个利用 Boost Log 库的底层行为的宏。例如,BOOST_LOG_SEV 是:

#define BOOST_LOG_SEV(logger, lvl) BOOST_LOG_STREAM_SEV(logger, lvl)
#define BOOST_LOG_STREAM_SEV(logger, lvl)\
    BOOST_LOG_STREAM_WITH_PARAMS((logger), (::boost::log::keywords::severity = (lvl)))

使用BOOST_LOG_STREAM_WITH_PARAMS,您可以设置和获取更多属性,如下所示:

// New macro that includes severity, filename and line number
#define CUSTOM_LOG(logger, sev) \
   BOOST_LOG_STREAM_WITH_PARAMS( \
      (logger), \
         (set_get_attrib("File", path_to_filename(__FILE__))) \
         (set_get_attrib("Line", __LINE__)) \
         (::boost::log::keywords::severity = (boost::log::trivial::sev)) \
   )

// Set attribute and return the new value
template<typename ValueType>
ValueType set_get_attrib(const char* name, ValueType value) {
   auto attr = logging::attribute_cast<attrs::mutable_constant<ValueType>>(logging::core::get()->get_thread_attributes()[name]);
   attr.set(value);
   return attr.get();
}

// Convert file path to only the filename
std::string path_to_filename(std::string path) {
   return path.substr(path.find_last_of("/\\")+1);
}

完整的源代码是:

#include <boost/log/trivial.hpp>
#include <boost/log/sources/severity_logger.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/console.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/attributes/mutable_constant.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/log/support/date_time.hpp>
#include <boost/log/attributes/mutable_constant.hpp>

namespace logging  = boost::log;
namespace attrs    = boost::log::attributes;
namespace expr     = boost::log::expressions;
namespace src      = boost::log::sources;
namespace keywords = boost::log::keywords;

// New macro that includes severity, filename and line number
#define CUSTOM_LOG(logger, sev) \
   BOOST_LOG_STREAM_WITH_PARAMS( \
      (logger), \
         (set_get_attrib("File", path_to_filename(__FILE__))) \
         (set_get_attrib("Line", __LINE__)) \
         (::boost::log::keywords::severity = (boost::log::trivial::sev)) \
   )

// Set attribute and return the new value
template<typename ValueType>
ValueType set_get_attrib(const char* name, ValueType value) {
   auto attr = logging::attribute_cast<attrs::mutable_constant<ValueType>>(logging::core::get()->get_thread_attributes()[name]);
   attr.set(value);
   return attr.get();
}

// Convert file path to only the filename
std::string path_to_filename(std::string path) {
   return path.substr(path.find_last_of("/\\")+1);
}

void init() {
   // New attributes that hold filename and line number
   logging::core::get()->add_thread_attribute("File", attrs::mutable_constant<std::string>(""));
   logging::core::get()->add_thread_attribute("Line", attrs::mutable_constant<int>(0));

   logging::add_file_log (
    keywords::file_name = "sample.log",
    keywords::format = (
     expr::stream
      << expr::format_date_time<boost::posix_time::ptime>("TimeStamp", "%Y-%m-%d_%H:%M:%S.%f")
      << ": <" << boost::log::trivial::severity << "> "
      << '['   << expr::attr<std::string>("File")
               << ':' << expr::attr<int>("Line") << "] "
      << expr::smessage
    )
   );
   logging::add_common_attributes();
}

int main(int argc, char* argv[]) {
   init();
   src::severity_logger<logging::trivial::severity_level> lg;

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

这会生成这样的日志:

2015-10-15_15:25:12.743153: <debug> [main.cpp:61] A regular message

【讨论】:

  • +1。看看它是如何实现的——如果你将属性类型定义为mutable_constant&lt;boost::log::string_literal&gt; 并用boost::log::string_literal(__FILE__) 等分配它应该会更快,因为它将停止在每个日志行上分配/复制字符串。
  • 好点。但是,__LINE__ 是一个整数常量,__FILE__ 用于获取此示例中的子字符串。 boost::log::string_literal 从数组常量构造,如 char value[N]
  • @Nature.Li 表示代码不是线程安全的。我在代码中更改了线程属性的全局属性,但是我没有用几个线程进行测试。
  • @GuillermoRuiz 嗨。你能分享线程安全代码吗?我也有一些线程问题。
  • 它可以在多线程代码中工作吗?这个解决方案的行号不一致
【解决方案2】:

正如 user2943014 所指出的,使用范围会打印您打开该范围的行号,而不是您使用 BOOST_LOG_SEV 发出日志消息的行号。

您可以使用属性在您实际记录的位置记录行号等。

在你的日志初始化函数中注册全局属性:

using namespace boost::log;
core::get()->add_global_attribute("Line", attributes::mutable_constant<int>(5));
core::get()->add_global_attribute("File", attributes::mutable_constant<std::string>(""));
core::get()->add_global_attribute("Function", attributes::mutable_constant<std::string>(""));

在您的日志记录宏中设置这些属性:

#define logInfo(methodname, message)                          \
  LOG_LOCATION;                                               \
  BOOST_LOG_SEV(_log, boost::log::trivial::severity_level::trace) << message

#define LOG_LOCATION                            \
  boost::log::attribute_cast<boost::log::attributes::mutable_constant<int>>(boost::log::core::get()->get_global_attributes()["Line"]).set(__LINE__); \
  boost::log::attribute_cast<boost::log::attributes::mutable_constant<std::string>>(boost::log::core::get()->get_global_attributes()["File"]).set(__FILE__); \
  boost::log::attribute_cast<boost::log::attributes::mutable_constant<std::string>>(boost::log::core::get()->get_global_attributes()["Function"]).set(__func__);

不是很漂亮,但它很有效,对我来说还有很长的路要走。遗憾的是,boost 没有开箱即用地提供此功能。

【讨论】:

  • 我觉得不错。以后会试试的
【解决方案3】:

我建议使用boost::log::add_value() 函数。

定义:

#define LOG_LOCATION(LEVEL, MSG)      \
  BOOST_LOG_SEV(logger::get(), LEVEL)     \
    << boost::log::add_value("Line", __LINE__)          \
    << boost::log::add_value("File", __FILE__)          \
    << boost::log::add_value("Function", __FUNCTION__) << MSG

然后你可以如下格式化:

boost::log::add_common_attributes();

boost::log::register_simple_filter_factory<boost::log::trivial::severity_level, char>("Severity");
boost::log::register_simple_formatter_factory<boost::log::trivial::severity_level, char>("Severity");

auto syslog_format(
    boost::log::expressions::stream <<
        "["   << boost::log::expressions::format_date_time< boost::posix_time::ptime >("TimeStamp", "%Y-%m-%d %H:%M:%S") <<
        "] [" << boost::log::expressions::attr<boost::log::attributes::current_thread_id::value_type>("ThreadID") << 
        "] [" << std::left << std::setw(7) << std::setfill(' ') << boost::log::trivial::severity <<
        "] "  << boost::log::expressions::smessage <<
        " ("  << boost::log::expressions::attr<std::string>("Filename") <<
        ":"   << boost::log::expressions::attr<int>("Line") <<
        ":"   << boost::log::expressions::attr<std::string>("Function") <<
        ")"
);

boost::log::add_file_log(
    boost::log::keywords::file_name  = "sys_%d_%m_%Y.%N.log",
    boost::log::keywords::format = syslog_format
);

无需添加全局属性,如上所示,您可以轻松地对其进行格式化。我发现这是其他解决方案和原始 __FILE__ __LINE__ 方法之间的一个很好的折衷方案。

完整示例here

【讨论】:

  • 我知道这是一个旧线程,但对于那些通过搜索来到这里的人,我发现(像其他人一样)Guillermo Ruiz 解决方案不是线程安全的,但这个似乎是(使用 logger_mt等),并且似乎更直接。
【解决方案4】:

定义

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 来记录文件和行的简单方法。

【讨论】:

    猜你喜欢
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    • 2010-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-07
    相关资源
    最近更新 更多