Cpp库_Spdlog_写日志

 spdlog 支持only-header(仅头文件)

 头文件下载,可以去官网 https://github.com/gabime/spdlog

或者:https://download.csdn.net/download/htj10/88421316?spm=1001.2014.3001.5503

使用:

1. 将spdlog头文件 include文件夹 拷贝到项目里

2. 工程属性,添加include路径到“附加包含目录”

 

// MyLearnSpdlog.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

/*
1. 将spdlog头文件 include文件夹 拷贝到项目里
2. 工程属性,添加include路径到“附加包含目录”
*/
#include <iostream>
#include "spdlog/fmt/fmt.h"
#include "spdlog/spdlog.h"
#include "spdlog/sinks/basic_file_sink.h"
#include "spdlog/sinks/rotating_file_sink.h"

void rotating_example();


int main()
{
    // fmt 使用
    auto s = fmt::format("{}_{}", "hello", 101);
    std::cout << s << '\n';//hello_101
    auto s2 = fmt::format("{2}_{1}_{0}_{1}", "hello", 101, 9.1);
    std::cout << s2 << '\n';//9.1_101_hello_101
    
    // 写日志(写到控制台)
    spdlog::info("hello...");
    spdlog::warn("hello2..");
    spdlog::error("hello3..");

    // 写日志(写到文件里)
    // Create basic file logger (not rotated).
    //auto my_logger = spdlog::basic_logger_mt("file_logger", "logs/basic-log.txt", true);//true -> 清空后写入
    auto my_logger = spdlog::basic_logger_mt("file_logger", "logs/basic-log.txt", false);//false -> 在文件结尾追加写入
    my_logger->info("中午好");
    my_logger->info("{},中午好","Lee");
    /*
[2023-10-12 18:37:19.670] [file_logger] [info] 中午好
[2023-10-12 18:37:19.670] [file_logger] [info] Lee,中午好
    */

    rotating_example();
}

void rotating_example()
{
    // Create a file rotating logger with 5mb size max and 3 rotated files. 
    // 每超过最大字节后,切换一个文件,若是max_files=3,
    // 最终会有四个文件(从新到旧):rotating.txt、rotating.1.txt、rotating.2.txt、rotating.3.txt
    // auto rotating_logger = spdlog::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3);
    auto rotating_logger = spdlog::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 100 * 1, 3);//这是追加写
    rotating_logger->set_level(spdlog::level::debug);
    rotating_logger->debug("hello,world.1");
    rotating_logger->debug("hello,world.2");
    rotating_logger->debug("hello,world.3");
    rotating_logger->debug("hello,world.4");
    rotating_logger->debug("hello,world.5");
    rotating_logger->debug("hello,world.6");
    rotating_logger->info("hello,world.7");
    rotating_logger->error("hello,world.8");
    rotating_logger->warn("hello,world.8");
    rotating_logger->debug("hello,world.9");
    rotating_logger->debug("hello,world.");
    rotating_logger->debug("{},{}.", "HELLO", "WORLD");
}

 

posted @ 2023-10-12 18:48  htj10  阅读(61)  评论(0编辑  收藏  举报
TOP