Boost之log日志使用

news/2024/12/28 9:15:00/

不讲理论,直接上在程序中可用代码:
一、引入Boost模块

开发环境:Visual Studio 2017
Boost库版本:1.68.0
安装方式:Nuget
安装命令:

#只安装下面几个即可
Install-package boost -version 1.68.0
Install-package boost_filesystem-vc141 -version 1.68.0
Install-package boost_log_setup-vc141 -version 1.68.0
Install-package boost_log-vc141 -version 1.68.0#这里是其他模块,可不安装
Install-package boost_atomic-vc141 -version 1.68.0
Install-package boost_chrono-vc141 -version 1.68.0
Install-package boost_date_time-vc141 -version 1.68.0
Install-package boost_system-vc141 -version 1.68.0
Install-package boost_thread-vc141 -version 1.68.0
Install-package boost_locale-vc141 -version 1.68.0

调用Nuget控制台:

 

二、引入下面两个hpp文件
boost_logger.hpp

#pragma once#include <string>
#include <fstream>
#include <iostream>
#include <boost/filesystem.hpp>
#include <boost/smart_ptr/shared_ptr.hpp>
#include <boost/core/null_deleter.hpp>
#include <boost/log/core.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/sinks/async_frontend.hpp>
#include <boost/log/sinks/text_ostream_backend.hpp>
#include <boost/log/sources/record_ostream.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/support/date_time.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/sources/severity_logger.hpp>
#include <boost/log/attributes/current_thread_id.hpp>
#include <boost/log/attributes/current_process_name.hpp>
#include <boost/log/attributes/attribute.hpp>
#include <boost/log/attributes/attribute_cast.hpp>
#include <boost/log/attributes/attribute_value.hpp>
#include <boost/log/sinks/async_frontend.hpp>// Related headersQDebug
#include <boost/log/sinks/unbounded_fifo_queue.hpp>
#include <boost/log/sinks/unbounded_ordering_queue.hpp>
#include <boost/log/sinks/bounded_fifo_queue.hpp>
#include <boost/log/sinks/bounded_ordering_queue.hpp>
#include <boost/log/sinks/drop_on_overflow.hpp>
#include <boost/log/sinks/block_on_overflow.hpp>//这里是logger的头文件,后面根据实际路径引入
#include "logger.hpp"//引入各种命名空间
namespace logging = boost::log;
namespace src = boost::log::sources;
namespace expr = boost::log::expressions;
namespace sinks = boost::log::sinks;
namespace keywords = boost::log::keywords;
namespace attrs = boost::log::attributes;
//建立日志源,支持严重属性
thread_local static boost::log::sources::severity_logger<log_level> lg;#define BOOST_LOG_Q_SIZE 1000//创建输出槽:synchronous_sink是同步前端,允许多个线程同时写日志,后端无需考虑多线程问题
typedef sinks::asynchronous_sink<sinks::text_file_backend, sinks::bounded_fifo_queue<BOOST_LOG_Q_SIZE, sinks::block_on_overflow>> sink_t;
static std::ostream &operator<<(std::ostream &strm, log_level level)
{static const char *strings[] ={"debug","info","warn","error","critical"};if (static_cast<std::size_t>(level) < sizeof(strings) / sizeof(*strings))strm << strings[level];elsestrm << static_cast<int>(level);return strm;
}
class boost_logger : public logger_iface
{
public:boost_logger(const std::string& dir) : m_level(log_level::error_level), dir(dir){}~boost_logger(){}/*** 日志初始化*/void init() override{//判断日志文件所在路径是否存在if (boost::filesystem::exists(dir) == false){boost::filesystem::create_directories(dir);}//添加公共属性logging::add_common_attributes();//获取日志库核心core = logging::core::get();//创建后端,并设值日志文件相关控制属性boost::shared_ptr<sinks::text_file_backend> backend = boost::make_shared<sinks::text_file_backend>(keywords::open_mode = std::ios::app, // 采用追加模式keywords::file_name = dir + "/%Y%m%d_%N.log", //归档日志文件名keywords::rotation_size = 10 * 1024 * 1024, //超过此大小自动建立新文件keywords::time_based_rotation = sinks::file::rotation_at_time_point(0, 0, 0), //每隔指定时间重建新文件keywords::min_free_space = 100 * 1024 * 1024  //最低磁盘空间限制);if (!_sink){_sink.reset(new sink_t(backend));//向日志源添加槽core->add_sink(_sink);}//添加线程ID公共属性core->add_global_attribute("ThreadID", attrs::current_thread_id());//添加进程公共属性core->add_global_attribute("Process", attrs::current_process_name());//设置过滤器_sink->set_filter(expr::attr<log_level>("Severity") >= m_level);// 如果不写这个,它不会实时的把日志写下去,而是等待缓冲区满了,或者程序正常退出时写下// 这样做的好处是减少IO操作,提高效率_sink->locked_backend()->auto_flush(true); // 使日志实时更新//这些都可在配置文件中配置_sink->set_formatter(expr::stream<< "["<< expr::attr<std::string>("Process") << ":" << expr::attr<attrs::current_thread_id::value_type>("ThreadID") << ":"<< expr::attr<unsigned int>("LineID") << "]["<< expr::format_date_time<boost::posix_time::ptime>("TimeStamp", "%Y-%m-%d %H:%M:%S.%f") << "]["<< expr::attr<log_level>("Severity") << "] "<< expr::smessage);}/*** 停止记录日志*/void stop() override{warn_log("boost logger stopping");_sink->flush();_sink->stop();core->remove_sink(_sink);}/*** 设置日志级别*/void set_log_level(log_level level) override{m_level = level;if (_sink){_sink->set_filter(expr::attr<log_level>("Severity") >= m_level);}}log_level get_log_level() override{return m_level;}void debug_log(const std::string &msg) override{BOOST_LOG_SEV(lg, debug_level) << msg << std::endl;}void info_log(const std::string &msg) override{BOOST_LOG_SEV(lg, info_level) << blue << msg << normal << std::endl;}void warn_log(const std::string &msg) override{BOOST_LOG_SEV(lg, warn_level) << yellow << msg << normal << std::endl;}void error_log(const std::string &msg) override{BOOST_LOG_SEV(lg, error_level) << red << msg << normal << std::endl;}void critical_log(const std::string &msg) override{BOOST_LOG_SEV(lg, critical_level) << red << msg << normal << std::endl;}private:log_level m_level;boost::shared_ptr<logging::core> core;boost::shared_ptr<sink_t> _sink;//日志文件路径const std::string& dir;
};

logger.hpp

#pragma once
#define BOOST_ALL_DYN_LINK#include <string>   // std::string
#include <iostream> // std::cout
#include <fstream>
#include <sstream> // std::ostringstream
#include <memory>typedef std::basic_ostringstream<char> tostringstream;
static const char black[] = {0x1b, '[', '1', ';', '3', '0', 'm', 0};
static const char red[] = {0x1b, '[', '1', ';', '3', '1', 'm', 0};
static const char yellow[] = {0x1b, '[', '1', ';', '3', '3', 'm', 0};
static const char blue[] = {0x1b, '[', '1', ';', '3', '4', 'm', 0};
static const char normal[] = {0x1b, '[', '0', ';', '3', '9', 'm', 0};
#define ACTIVE_LOGGER_INSTANCE (*activeLogger::getLoggerAddr())
// note: this will replace the logger instace. If this is not the first time to set the logger instance.
// Please make sure to delete/free the old instance.
#define INIT_LOGGER(loggerImpPtr)              \{                                           \ACTIVE_LOGGER_INSTANCE = loggerImpPtr;    \ACTIVE_LOGGER_INSTANCE->init();           \}
#define CHECK_LOG_LEVEL(logLevel) (ACTIVE_LOGGER_INSTANCE ? ((ACTIVE_LOGGER_INSTANCE->get_log_level() <= log_level::logLevel##_level) ? true : false) : false)
#define SET_LOG_LEVEL(logLevel)                                                   \{                                                                              \if (ACTIVE_LOGGER_INSTANCE)                                                  \(ACTIVE_LOGGER_INSTANCE->set_log_level(log_level::logLevel##_level));      \}
#define DESTROY_LOGGER                      \{                                        \if (ACTIVE_LOGGER_INSTANCE)            \{                                      \ACTIVE_LOGGER_INSTANCE->stop();      \delete ACTIVE_LOGGER_INSTANCE;       \}                                      \}enum log_level
{debug_level = 0,info_level,warn_level,error_level,critical_level
};class logger_iface
{
public:logger_iface(void) = default;virtual ~logger_iface(void) = default;logger_iface(const logger_iface &) = default;logger_iface &operator=(const logger_iface &) = default;public:virtual void init() = 0;virtual void stop() = 0;virtual void set_log_level(log_level level) = 0;virtual log_level get_log_level() = 0;virtual void debug_log(const std::string &msg) = 0;virtual void info_log(const std::string &msg) = 0;virtual void warn_log(const std::string &msg) = 0;virtual void error_log(const std::string &msg) = 0;virtual void critical_log(const std::string &msg) = 0;
};class activeLogger
{
public:static logger_iface **getLoggerAddr(){static logger_iface *activeLogger;return &activeLogger;}
};#define __LOGGING_ENABLED#ifdef __LOGGING_ENABLED
#define __LOG(level, msg)                                                       \\{                                                                            \tostringstream var;                                                        \var << "[" << __FILE__ << ":" << __LINE__ << ":" << __func__ << "] \n"     \<< msg;                                                                  \if (ACTIVE_LOGGER_INSTANCE)                                                \ACTIVE_LOGGER_INSTANCE->level##_log(var.str());                          \}
#else
#define __LOG(level, msg)
#endif /* __LOGGING_ENABLED */

三、使用样例

#include "logger/boost_logger.hpp"
#include "logger/simpleLogger.hpp"void testCustomLogger() {//初始化日志对象:日志路径后期从配置文件读取const std::string logDir = "E:\\log";INIT_LOGGER(new boost_logger(logDir));//设置过滤级别(可以读取配置文件)SET_LOG_LEVEL(debug);//输出各级别日志,(void *)ACTIVE_LOGGER_INSTANCE:代表激活的日志实例(可不写)__LOG(critical, "hello logger!"<< "this is critical log" << (void *)ACTIVE_LOGGER_INSTANCE);__LOG(debug, "hello logger!!!!!!!!!!!!!!!"<< "this is debug log");
}


http://www.ppmy.cn/news/1558750.html

相关文章

领域自适应

领域自适应&#xff08;Domain Adaptation&#xff09;是一种技术&#xff0c;用于将机器学习模型从一个数据分布&#xff08;源域&#xff09;迁移到另一个数据分布&#xff08;目标域&#xff09;。这在源数据和目标数据具有不同特征分布但任务相同的情况下特别有用。领域自适…

【Maven】Maven的快照库和发行库

1、分类 Maven 支持两种类型的仓库&#xff1a;快照库&#xff08;Snapshot Repository&#xff09;和发行库&#xff08;Release Repository&#xff09;&#xff0c;用于存储不同性质的构件&#xff08;Artifacts&#xff09;。 (1) 快照库 (Snapshot Repository)&#xff…

2024年种子轮融资趋势:科技引领,消费降温

引言 2024年的种子轮投资市场呈现出显著的技术驱动特征,尤其是在人工智能(AI)、软件即服务(SaaS)、网络安全、医疗科技以及深科技领域,投资者表现出了浓厚的兴趣。与此同时,传统消费品和直接面向消费者(DTC)零售等领域则遭遇了融资瓶颈。本文将深入分析这些变化背后的…

5G CPE接口扩展之轻量型多口千兆路由器小板选型

多口千兆路由器小板选型 方案一: 集成式5口千兆WIFI路由器小板方案二:交换板 + USBwifiUSB WIFI选型一USBwifi选型二:四口千兆选型一四口千兆选型二:四口千兆选型三:部分5G CPE主板不支持Wifi,并且网口数量较少,可采用堆叠方式进行网口和wifi功能 扩展,本文推荐一些路由…

ffmpeg 编译+ libx264

编译 libx264 将 libx264 生成结果拷贝到 msys64 的 usr\local 目录下。这样在 msys2_shell 中就可以使用 /usr/local 来找到这个路径了。 编译不设置 prefix&#xff0c;默认将文件拷贝到 /usr/local 编译 ffmpeg libx264 配置 pkg-config&#xff0c;不然编译找不到 libx26…

YFcmf-tp6验证码不通过,报错令牌数据无效

问题描述&#xff1a; linux安装了yfcmf&#xff0c;php的fpm进程修改了用户&#xff1b;导致在进系统的时候报了index/temp/..下面的权限不足&#xff0c;和admin/temp/下的权限不足&#xff1b;都给全777权限后&#xff0c;在登录的时候验证码一直不正确&#xff1b;提示令牌…

路由器刷机TP-Link tp-link-WDR566 路由器升级宽带速度

何在路由器上设置代理服务器&#xff1f; 如何在路由器上设置代理服务器&#xff1f; 让所有连接到该路由器的设备都能够享受代理服务器的好处是一个不错的选择&#xff0c;特别是当需要访问特定的网站或加速网络连接的时候。下面是一些您可以跟随的步骤&#xff0c;使用路由器…

arcface

GitHub - bubbliiiing/arcface-pytorch: 这是一个arcface-pytorch的源码&#xff0c;可以用于训练自己的模型。 https://github.com/deepinsight/insightface/tree/master/recognition/arcface_torch 参考博客 Arcface部署应用实战-CSDN博客 https://zhuanlan.zhihu.com/p/16…