Boost之log日志使用

不講理論,直接上在程序中可用代碼:
一、引入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.pswp.cn/web/64270.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/64270.shtml
英文地址,請注明出處:http://en.pswp.cn/web/64270.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

【MySQL】十四,MySQL 8.0的隱藏索引

在MySQL 8.0之前的版本中&#xff0c;索引只能直接刪除。如果刪除后發現引起了系統故障&#xff0c;又必須進行創建。當表的數據量比較大的時候&#xff0c;這樣做的代價就會非常高。 在MySQL 8.0中&#xff0c;提供了隱藏索引。如果想刪除某個索引&#xff0c;那么在實際刪除…

【ES6復習筆記】解構賦值(2)

介紹 解構賦值是一種非常方便的語法&#xff0c;可以讓我們更簡潔地從數組和對象中提取值&#xff0c;并且可以應用于很多實際開發場景中。 1. 數組的解構賦值 數組的解構賦值是按照一定模式從數組中提取值&#xff0c;然后對變量進行賦值。下面是一個例子&#xff1a; con…

爬蟲數據存儲:Redis、MySQL 與 MongoDB 的對比與實踐

爬蟲的核心任務是從網絡中提取數據&#xff0c;而存儲這些數據是流程中不可或缺的一環。根據業務需求的不同&#xff0c;存儲的選擇可能直接影響數據處理的效率和開發體驗。本文將介紹三種常用的存儲工具——Redis、MySQL 和 MongoDB&#xff0c;分析它們的特點&#xff0c;并提…

【Python】使用匿名函數Lambda解析html源碼的任意元素(Seleinium ,BeautifulSoup皆適用)

一直都發現lambda函數非常好用&#xff0c;它可以用簡潔的方式編寫小函數&#xff0c;無需寫冗長的過程就可以獲取結果。干脆利落&#xff01; 它允許我們定義一個匿名函數&#xff0c;在調用一次性的函數時非常有用。 最近整理了一些&#xff0c;lambda函數結合BeautifulSou…

Bash語言的語法

Bash語言簡介與應用 Bash&#xff08;Bourne Again SHell&#xff09;是一種Unix Shell和命令語言&#xff0c;在Linux、macOS及其他類Unix系統中被廣泛使用。作為GNU項目的一部分&#xff0c;Bash不僅是對早期Bourne Shell的增強&#xff0c;還引入了許多特性和功能&#xff…

Ingress-Nginx Annotations 指南:配置要點全方面解讀(下)

文章目錄 1.HTTP2 Push Preload2.Server Alias3.Server snippet4.Client Body Buffer Size5.External Authentication6.Global External Authentication7.Rate Limiting8.Global Rate Limiting9.Permanent Redirect10.Permanent Redirect Code11.Temporal Redirect12.SSL Passt…

互聯網路由架構

大家覺得有意義和幫助記得及時關注和點贊!!! 本書致力于解決實際問題&#xff0c;書中包含大量的架構圖、拓撲圖和真實場景示例&#xff0c;內容全面 且易于上手&#xff0c;是不可多得的良心之作。本書目的是使讀者成為將自有網絡集成到全球互聯網 領域的專家。 以下是筆記內…

【Flutter_Web】Flutter編譯Web第三篇(網絡請求篇):dio如何改造方法,變成web之后數據如何處理

前言 Flutter端在處理網絡請求的時候&#xff0c;最常用的庫當然是Dio了&#xff0c;那么在改造成web端的時候&#xff0c;最先處理的必然是網絡請求&#xff0c;否則沒有數據去處理驅動實圖渲染。 官方鏈接 pub https://pub.dev/packages/diogithub https://github.com/c…

Spring Boot @Conditional注解

在Spring Boot中&#xff0c;Conditional 注解用于條件性地注冊bean。這意味著它可以根據某些條件來決定是否應該創建一個特定的bean。這個注解可以放在配置類或方法上&#xff0c;并且它會根據提供的一組條件來判斷是否應該實例化對應的組件。 要使用 Conditional注解時&#…

項目上傳到gitcode

首先需要在個人設置里面找到令牌 記住自己的賬號和訪問令牌&#xff08;一長串&#xff09;&#xff0c;后面git要輸入這個&#xff0c; 賬號是下面這個 來到自己的倉庫 #查看遠程倉庫&#xff0c;是不是自己的云倉庫 git remote -v # 創建新分支 git checkout -b llf # 三步…

【Rust自學】6.4. 簡單的控制流-if let

喜歡的話別忘了點贊、收藏加關注哦&#xff0c;對接下來的教程有興趣的可以關注專欄。謝謝喵&#xff01;(&#xff65;ω&#xff65;) 6.4.1. 什么是if let if let語法允許將if和let組合成一種不太冗長的方式來處理與一種模式匹配的值&#xff0c;同時忽略其余模式。 可以…

【Git學習】windows系統下git init后沒有看到生成的.git文件夾

[問題] git init 命令后看不到.git文件夾 [原因] 文件夾設置隱藏 [解決辦法] Win11 win10

vscode添加全局宏定義

利用vscode編輯代碼時&#xff0c;設置了禁用非活動區域著色后&#xff0c;在一些編譯腳本中配置的宏又識別不了 遇到#ifdef包住的代碼就會變暗色&#xff0c;想查看代碼不是很方便。如下圖&#xff1a; 一 解決&#xff1a; 在vscode中添加全局宏定義。 二 步驟&#xff1a…

【服務器主板】定制化:基于Intel至強平臺的全新解決方案

隨著數據處理需求不斷增長&#xff0c;服務器硬件的發展也在持續推進。在這一背景下&#xff0c;為用戶定制了一款全新的基于Intel至強平臺的服務器主板&#xff0c;旨在提供強大的計算能力、優異的內存支持以及高速存儲擴展能力。適用于需要高性能計算、大規模數據處理和高可用…

php怎么去除數點后面的0

在PHP中&#xff0c;我們可以使用幾種方法來去除數字小數點后的0。 方法一&#xff1a;使用intval函數 intval函數可以將一個數字轉化為整數&#xff0c;另外&#xff0c;它也可以去除小數點后面的0。 “php $number 123.4500; $number intval($number); echo $number; // 輸…

數字后端培訓項目Floorplan常見問題系列專題續集1

今天繼續給大家分享下數字IC后端設計實現floorplan階段常見問題系列專題。這些問題都是來自于咱們社區IC后端訓練營學員提問的問題庫。目前這部分問題庫已經積累了4年了&#xff0c;后面會陸續分享這方面的問題。 希望對大家的數字后端學習和工作有所幫助。 數字后端項目Floor…

【遞歸,搜索與回溯算法 綜合練習】深入理解暴搜決策樹:遞歸,搜索與回溯算法綜合小專題(二)

優美的排列 題目解析 算法原理 解法 &#xff1a;暴搜 決策樹 紅色剪枝&#xff1a;用于剪去該節點的值在對應分支中&#xff0c;已經被使用的情況&#xff0c;可以定義一個 check[ ] 紫色剪枝&#xff1a;perm[i] 不能夠被 i 整除&#xff0c;i 不能夠被 per…

Java中各種數組復制方式的效率對比

在 Java 中&#xff0c;數組復制是一個常見的操作&#xff0c;尤其是在處理動態數組&#xff08;如 ArrayList&#xff09;時。Java 提供了多種數組復制的方式&#xff0c;每種方式在性能和使用場景上都有所不同。以下是對幾種主要數組復制方式的比較&#xff0c;包括 System.a…

視頻會議是如何實現屏幕標注功能的?

現在主流的視頻會議軟件都有屏幕標注功能&#xff0c;屏幕標注功能給屏幕分享者講解分享內容時提供了極大的方便。那我們以傲瑞視頻會議&#xff08;OrayMeeting&#xff09;為例&#xff0c;來講解屏幕標注是如何實現的。 傲瑞會議的PC端&#xff08;Windows、信創Linux、銀河…

Framework開發入門(一)之源碼下載

一、使用Linux操作系統的小伙伴可以跳轉到官網鏈接按提示操作 官網源碼地址&#xff1a;下載源代碼 | Android Open Source Project 1.創建一個空目錄來存放您的工作文件。為其指定一個您喜歡的任意名稱&#xff1a; mkdir WORKING_DIRECTORYcdWORKING_DIRECTORY …