阅读量:1
在Ubuntu中配置C++日志系统,你可以选择多种日志库,例如spdlog、glog、log4cpp等。这里以spdlog为例,介绍如何在Ubuntu中配置和使用C++日志系统。
安装spdlog
-
通过包管理器安装:
sudo apt update sudo apt install libspdlog-dev -
通过源码编译安装:
- 下载spdlog源码:
git clone https://github.com/gabime/spdlog.git cd spdlog - 编译并安装:
mkdir build && cd build cmake .. make -j$(nproc) sudo make install
- 下载spdlog源码:
在C++项目中使用spdlog
-
创建一个新的C++项目:
mkdir my_project cd my_project mkdir src cd src -
编写C++代码: 创建一个名为
main.cpp的文件,并添加以下内容:#include#include "spdlog/spdlog.h" #include "spdlog/sinks/stdout_color_sinks.h" int main() { // 创建一个控制台日志记录器 auto console = spdlog::stdout_color_mt("console"); // 设置日志级别 console->set_level(spdlog::level::debug); // 记录不同级别的日志 console->trace("Trace message"); console->debug("Debug message"); console->info("Info message"); console->warn("Warning message"); console->error("Error message"); console->critical("Critical message"); return 0; } -
编写CMakeLists.txt: 创建一个名为
CMakeLists.txt的文件,并添加以下内容:cmake_minimum_required(VERSION 3.10) project(MyProject) set(CMAKE_CXX_STANDARD 14) # 查找spdlog库 find_package(spdlog REQUIRED) add_executable(MyProject main.cpp) # 链接spdlog库 target_link_libraries(MyProject spdlog::spdlog) -
编译项目: 在项目根目录下运行以下命令:
mkdir build && cd build cmake .. make -
运行程序:
./MyProject
你应该会看到类似以下的输出:
[2023-04-15 12:34:56.789] [console] [trace] Trace message
[2023-04-15 12:34:56.789] [console] [debug] Debug message
[2023-04-15 12:34:56.789] [console] [info] Info message
[2023-04-15 12:34:56.789] [console] [warn] Warning message
[2023-04-15 12:34:56.789] [console] [error] Error message
[2023-04-15 12:34:56.789] [console] [critical] Critical message
通过这种方式,你可以在Ubuntu中配置和使用C++日志系统。根据你的需求,你可以进一步探索spdlog的其他功能,例如文件日志记录、异步日志记录等。
以上就是关于“如何在Ubuntu中配置C++日志系统”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm