提升日志以打印源代码文件名和行号

时间:2014-07-15 05:09:27

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

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

[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 个答案:

答案 0 :(得分:12)

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

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

您可以更好地创建利用Boost日志库的基础行为的宏。例如, 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 :(得分:6)

正如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__);

不完全漂亮,但它有效,对我来说还有很长的路要走。可惜的是,并没有提供开箱即用的功能。

答案 2 :(得分: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的情况下记录文件和行的简单方法。

答案 3 :(得分:0)

我建议使用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