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");
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章