21

我在我的 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;
}
4

4 回答 4

15

正如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
于 2015-10-15T14:32:59.400 回答
9

正如 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 没有开箱即用地提供此功能。

于 2015-08-25T14:15:23.073 回答
5

我建议使用该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__方法之间的一个很好的折衷方案。

完整的例子在这里

于 2019-02-13T17:05:23.447 回答
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 回答