spdlog日志库--输出格式(fmt 库集成)
系列目录
spdlog日志库–基础介绍
spdlog日志库–源码解析
文章目录
- 1. 格式输出
- fmt格式输出
- 2. format_spec 格式空间
- 正数和负数的格式
- #号控制输出格式
- 3. %s占位符 切换 {}占位符 (fmtlib(fmt::format))
- {}占位符 -> %s等占位符
- %s占位符 -> {}占位符
- 4. 不使用占位符({}、%s等)格式输出的其他方式
- 参考链接
1. 格式输出
fmt格式输出
使用fmtlib直接格式化(非spdlog内置)
虽然spdlog不直接使用{}作为占位符,但你可以在使用spdlog之前,使用fmtlib(spdlog的底层库)来格式化你的日志消息。
基础:
#include "fmt/core.h"
#include "spdlog/spdlog.h" int main() { auto logger = spdlog::stdout_color_mt("my_logger"); int value = 42; //std::string formatted_message = fmt::format("The value is: {}", value); //logger->info(formatted_message); logger->info("Hello {}", "world" );return 0;
}[2022-02-04 14:54:25.083] [info] Hello world
多参数形式:
方式一:第一个大括号内对应后面第一个参数 第二个大括号内对应第二个参数
spdlog::info("nice to {} {}", "meet" , "you");0 1 0 1
[2022-02-04 15:41:37.131] [info] nice to meet you
方式二:大括号内输入整数,1代表参数后面以第二个数值,0代表参数后面第一个数值,以此类推。
spdlog::info("nice to {1} {0}", "you" , "meet");1 0 0 1
[2022-02-04 15:48:07.328] [info] nice to meet you
说明: 大括号内的数字是参数标识符,它按照顺序排列。
例如:
spdlog::info("The last letter in the Alaphbet is {25}","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z");[2022-02-04 17:13:43.973] [info] The last letter in the Alaphbet is z
如果想在有参数的字符串内输出大括号,需要采取下面的代码
spdlog::info(" {{}} {}","left is curly brace");0 0
[2022-02-04 17:42:19.961] [info] {} left is curly brace
或者
spdlog::info(" {1} {0}","{}","right is curly brace");[2022-02-04 17:53:54.641] [info] right is curly brace {}
2. format_spec 格式空间
大括号内的内容 可以是格式空间format_spec
或者时间格式空间chrono_format_spec
格式空间语法
format_spec = [[fill]align][sign]["#"]["0"][width]["." precision]["L"][type]
对齐 align 其左边的填充可以选 (注意 format_spec 或 chrono_format_spec 在大括号内的“:”之后添加)
align = "<" | ">" | "^"“<” = 左对齐
“>” = 右对齐“^” = 居中
代码块内(1、 2、 3上方 align后)没有说明宽度 默认空一格
spdlog::info("{:^} {:<} {:>}", "first","second","third");1 2 3