Files
spdlog/example/example.cpp

299 lines
11 KiB
C++
Raw Permalink Normal View History

2024-12-06 19:21:42 +02:00
//
2019-03-24 00:40:27 +02:00
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
2019-05-12 17:05:14 +03:00
2019-03-24 00:40:27 +02:00
// spdlog usage example
2021-09-03 10:53:29 -07:00
#include <chrono>
2023-09-29 00:20:26 +03:00
#include <cstdio>
2019-12-13 16:17:09 +02:00
void stdout_logger_example();
void basic_example();
void rotating_example();
void daily_example();
void callback_example();
2019-12-13 16:17:09 +02:00
void async_example();
void binary_example();
void vector_example();
2020-08-29 02:48:43 +03:00
void stopwatch_example();
2019-12-13 16:17:09 +02:00
void trace_example();
void multi_sink_example();
void user_defined_example();
void err_handler_example();
void syslog_example();
void udp_example();
2021-09-03 10:53:29 -07:00
void custom_flags_example();
2021-11-15 14:32:34 +02:00
void file_events_example();
2024-12-06 19:21:42 +02:00
void replace_global_logger_example();
2023-09-29 00:20:26 +03:00
#include "spdlog/spdlog.h"
2024-11-29 16:15:13 +02:00
#include "spdlog/version.h"
2019-08-22 19:58:49 +03:00
using namespace spdlog::sinks;
int main(int, char *[]) {
2024-01-13 09:37:32 +02:00
spdlog::info("Welcome to spdlog version {}.{}.{} !", SPDLOG_VER_MAJOR, SPDLOG_VER_MINOR, SPDLOG_VER_PATCH);
2020-09-26 15:30:45 +03:00
spdlog::warn("Easy padding in numbers like {:08d}", 12);
spdlog::critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42);
spdlog::info("Support for floats {:03.2f}", 1.23456);
spdlog::info("Positional args are {1} {0}..", "too", "supported");
spdlog::info("{:>8} aligned, {:<8} aligned", "right", "left");
// Runtime log levels
2023-09-25 16:40:05 +03:00
spdlog::set_level(spdlog::level::info); // Set global log level to info
2020-09-26 15:30:45 +03:00
spdlog::debug("This message should not be displayed!");
2023-09-25 16:40:05 +03:00
spdlog::set_level(spdlog::level::trace); // Set specific logger's log level
2020-09-26 15:30:45 +03:00
spdlog::debug("This message should be displayed..");
// Customize msg format for all loggers
spdlog::set_pattern("[%H:%M:%S %z] [%^%L%$] [thread %t] %v");
spdlog::info("This an info message with custom format");
2023-09-25 16:40:05 +03:00
spdlog::set_pattern("%+"); // back to default format
spdlog::set_level(spdlog::level::info);
2020-09-26 15:30:45 +03:00
try {
2020-09-26 15:30:45 +03:00
stdout_logger_example();
basic_example();
rotating_example();
daily_example();
callback_example();
2020-09-26 15:30:45 +03:00
async_example();
binary_example();
vector_example();
2020-09-26 15:30:45 +03:00
multi_sink_example();
user_defined_example();
2021-11-15 14:54:51 +02:00
err_handler_example();
2020-09-26 15:30:45 +03:00
trace_example();
stopwatch_example();
udp_example();
2021-09-03 10:53:29 -07:00
custom_flags_example();
2021-11-15 14:32:34 +02:00
file_events_example();
2024-12-06 19:21:42 +02:00
replace_global_logger_example();
2020-09-26 15:30:45 +03:00
2024-12-06 19:21:42 +02:00
// Release all spdlog resources
2020-09-26 15:30:45 +03:00
// This is optional (only mandatory if using windows + async log).
spdlog::shutdown();
}
// Exceptions will only be thrown upon failed logger or sink construction (not during logging).
catch (const spdlog::spdlog_ex &ex) {
2020-09-26 15:30:45 +03:00
std::printf("Log initialization failed: %s\n", ex.what());
return 1;
}
}
#include "spdlog/sinks/stdout_color_sinks.h"
// or #include "spdlog/sinks/stdout_sinks.h" if no colors needed.
void stdout_logger_example() {
2024-01-13 09:37:32 +02:00
// Create color multithreading logger.
auto console = spdlog::create<stdout_color_sink_mt>("console");
2020-09-26 15:30:45 +03:00
// or for stderr:
2025-01-17 20:59:46 +02:00
// auto console = spdlog::create<stderr_color_sink_mt>("console");
2020-09-26 15:30:45 +03:00
}
#include "spdlog/sinks/basic_file_sink.h"
void basic_example() {
2020-09-26 15:30:45 +03:00
// Create basic file logger (not rotated).
auto my_logger = spdlog::create<basic_file_sink_mt>("file_logger", "logs/basic-log.txt", true);
2020-09-26 15:30:45 +03:00
}
#include "spdlog/sinks/rotating_file_sink.h"
void rotating_example() {
2020-09-26 15:30:45 +03:00
// Create a file rotating logger with 5mb size max and 3 rotated files.
auto rotating_logger = spdlog::create<rotating_file_sink_mt>("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3);
2020-09-26 15:30:45 +03:00
}
#include "spdlog/sinks/daily_file_sink.h"
void daily_example() {
2020-09-26 15:30:45 +03:00
// Create a daily logger - a new file is created every day on 2:30am.
auto daily_logger = spdlog::create<daily_file_format_sink_mt>("daily_logger", "logs/daily.txt", 2, 30);
2020-09-26 15:30:45 +03:00
}
#include "spdlog/sinks/callback_sink.h"
void callback_example() {
// Create the logger
auto logger = spdlog::create<callback_sink_mt>("custom_callback_logger", [](const spdlog::details::log_msg & /*msg*/) {
2024-01-13 09:37:32 +02:00
// do what you need to do with msg
});
}
#include "spdlog/sinks/async_sink.h"
void async_example() {
using spdlog::sinks::async_sink;
auto sink = async_sink::with<basic_file_sink_mt>("logs/async_log.txt", true);
auto logger = std::make_shared<spdlog::logger>("async_logger", sink);
for (int i = 1; i < 101; ++i) {
logger->info("Async message #{}", i);
2020-09-26 15:30:45 +03:00
}
}
// Log binary data as hex.
// Many types of std::container<char> types can be used.
// Iterator ranges are supported too.
// Format flags:
// {:X} - print in uppercase.
// {:s} - don't separate each byte with space.
// {:p} - don't print the position on each line start.
// {:n} - don't split the output to lines.
#include "spdlog/bin_to_hex.h"
void binary_example() {
2023-12-22 14:37:50 +02:00
std::vector<char> buf;
for (int i = 0; i < 80; i++) {
2020-09-26 15:30:45 +03:00
buf.push_back(static_cast<char>(i & 0xff));
}
spdlog::info("Binary example: {}", spdlog::to_hex(buf));
2024-01-13 09:37:32 +02:00
spdlog::info("Another binary example:{:n}", spdlog::to_hex(std::begin(buf), std::begin(buf) + 10));
2020-09-26 15:30:45 +03:00
// more examples:
// logger->info("uppercase: {:X}", spdlog::to_hex(buf));
// logger->info("uppercase, no delimiters: {:Xs}", spdlog::to_hex(buf));
// logger->info("uppercase, no delimiters, no position info: {:Xsp}", spdlog::to_hex(buf));
// logger->info("hexdump style: {:a}", spdlog::to_hex(buf));
// logger->info("hexdump style, 20 chars per line {:a}", spdlog::to_hex(buf, 20));
}
// Log a vector of numbers
#include "fmt/ranges.h"
void vector_example() {
std::vector<int> vec = {1, 2, 3};
spdlog::info("Vector example: {}", vec);
}
2020-09-26 15:30:45 +03:00
// Compile time log levels.
// define SPDLOG_ACTIVE_LEVEL to required level (e.g. SPDLOG_LEVEL_TRACE)
void trace_example() {
2024-12-06 19:21:42 +02:00
// trace from global logger
2020-09-26 15:30:45 +03:00
SPDLOG_TRACE("Some trace message.. {} ,{}", 1, 3.23);
2024-12-06 19:21:42 +02:00
// debug from global logger
2020-09-26 15:30:45 +03:00
SPDLOG_DEBUG("Some debug message.. {} ,{}", 1, 3.23);
}
// stopwatch example
#include <thread>
2023-09-29 00:20:26 +03:00
#include "spdlog/stopwatch.h"
void stopwatch_example() {
2020-09-26 15:30:45 +03:00
spdlog::stopwatch sw;
std::this_thread::sleep_for(std::chrono::milliseconds(123));
spdlog::info("Stopwatch: {} seconds", sw);
}
2021-09-05 11:35:00 +03:00
#include "spdlog/sinks/udp_sink.h"
void udp_example() {
udp_sink_config cfg("127.0.0.1", 11091);
auto my_logger = spdlog::create<udp_sink_mt>("udplog", cfg);
my_logger->set_level(spdlog::level::debug);
2021-09-03 16:36:49 -07:00
my_logger->info("hello world");
}
2020-09-26 15:30:45 +03:00
// A logger with multiple sinks (stdout and file) - each with a different format and log level.
void multi_sink_example() {
auto console_sink = std::make_shared<stdout_color_sink_mt>();
console_sink->set_level(spdlog::level::warn);
2020-09-26 15:30:45 +03:00
console_sink->set_pattern("[multi_sink_example] [%^%l%$] %v");
auto file_sink = std::make_shared<basic_file_sink_mt>("logs/multisink.txt", true);
file_sink->set_level(spdlog::level::trace);
2020-09-26 15:30:45 +03:00
spdlog::logger logger("multi_sink", {console_sink, file_sink});
logger.set_level(spdlog::level::debug);
2021-08-26 18:50:55 -07:00
logger.warn("this should appear in both console and file");
logger.info("this message should not appear in the console, only in the file");
}
2020-09-26 15:30:45 +03:00
2021-12-04 14:53:16 +02:00
// User defined types logging
struct my_type {
Synchronize v2.x With Changes from v1.x (#3581) * docs(tasks): v1.x inventory, triage template, merge report; update task checklist - Record merge-base and export v1-only commits (v2..v1) - Document failed merge attempt: v2 file tree diverges from v1 - Mark completed checklist items 0.x, 1.x, merge report draft (5.2) Made-with: Cursor * fix(pattern): %z with UTC pattern time shows +00:00 (port v1 09a674b7) - z_formatter takes pattern_time_type; emit +00:00 when pattern uses UTC - Track port in tasks/commits-ported.txt and merge-report; update checklist Made-with: Cursor * fix(os): Windows utc_minutes_offset via mktime/_mkgmtime (port v1 b656d1ce) - Replace GetTimeZoneInformation-based offset with v1.x mktime/_mkgmtime approach - Add tests/test_timezone.cpp and extend pattern_formatter tests; update os.h comment Made-with: Cursor * test(timezone): POSIX TZ with DST rules; include fcntl in tcp_client_unix (v1 ports) - 0f7562a0: EST5EDT / IST-2IDT macros for POSIX vs Windows - d2100d5d: fcntl.h for Unix tcp client header (v2 path) Made-with: Cursor * feat(tcp): connect timeouts and socket IO timeouts; ci: checkout@v6 (v1 ports) - 9ecdf5c8: connect_socket_with_timeout on Unix/Windows; tcp_sink timeout_ms - 3c61b051: actions/checkout@v6 on all workflows - tcp_sink: remove duplicate #pragma once Made-with: Cursor * feat(dup_filter_sink): ctor with sink list (v1 45b67eee); add full v1 SHA triage table - tasks/v1-triage-complete.md: 245 commits PORTED/PENDING/N/A for PRD 3A tracking - Merge report and task checklist updated Made-with: Cursor * feat(level): case-insensitive level_from_str; cmake: BUILD_TYPE only if top-level (v1 ports) - 566b2d14: common.cpp + test_misc (SUPERSEDED note for d5af52d9 in triage) - dd3ca04a: guard default CMAKE_BUILD_TYPE for add_subdirectory consumers - Update v1-triage-complete.md counts and statuses Made-with: Cursor * v1 parity: MSVC UTF-8, ansicolor/syslog/os, getenv, triage docs - CMake: SPDLOG_MSVC_UTF8 + /utf-8 for real MSVC only - ansicolor: protected target_file_; fix set_color_mode_ lock nesting - os: drop redundant fileapi.h; spdlog::details::os::getenv via std::getenv - tests: stopwatch waits 500ms; includes/triage/commits-ported/merge-report updates - Reclassify superseded v1 SHAs (Sep, syslog, stopwatch ms, utf8 tests, etc.) Made-with: Cursor * parity: ringbuffer zero capacity, utf8 assert; v1 triage sync - ringbuffer_sink: throw if n_items==0 (#3436); test expects spdlog_ex - utf8_to_wstrbuf: assert compares int to static_cast<int>(target.size()) (#3479) - Triage: PORTED ad725d34 getenv, 677a2d93 stopwatch, 3f7e5028, a6215527; SUPERSEDED a45c9390, eeb22c13, 5673e9e5, fe4f9952, 287333ee - tasks: 27 PORTED / 26 SUPERSEDED / 78 PENDING; merge-report + commits-ported Made-with: Cursor * docs(tasks): note regular commits and push after parity ports Made-with: Cursor * parity: dup_filter_sink notification level from last duplicate (#3390) - Remove notification_level ctor arg; track skipped_msg_log_level_ on duplicate skips - Test: skipped summary line uses same short level as duplicated messages - Triage: 847db337 PORTED; 28/26/77 counts; merge-report + commits-ported Made-with: Cursor * parity: UWP getenv (WINAPI_FAMILY); triage fmt/cfg/no-except - os_windows: detect non-desktop/UWP for empty getenv (#3489) - Triage: PORTED 8806ca65; SUPERSEDED e3f5a4fe e655dbb6; N/A ae1de0dc 548b2642 - Counts 29/28/116/72; merge-report + commits-ported Made-with: Cursor * parity: qt_sinks sign casts (#3487); triage 9c582574 superseded - qt_color_sink: qsizetype for UTF-8 color range lengths; index colors_ with size_t - SUPERSEDED: 9c582574 — os_unix utc_minutes_offset already matches #3366 - Counts 30/29/70; merge-report + commits-ported Made-with: Cursor * parity: SPDLOG_NO_TZ_OFFSET (#3483); triage #3360 superseded - CMake: option SPDLOG_NO_TZ_OFFSET; PUBLIC compile definition when ON - z_formatter: +??:?? when macro; else keep UTC +00:00 and local offset - utc_minutes_offset: stub on Unix/Windows when macro - test_pattern_formatter: %z UTC case matches placeholder when NO_TZ - SUPERSEDED 10320184 (ScopedPadder / %D already in v2) - Triage 31/30/68; merge-report + commits-ported Made-with: Cursor * triage: supersede 5931a3d6 ba508057 47b7e7c7 (already on v2 tree) Made-with: Cursor * tasks: sync 5.1 triage counts (33 superseded, 65 pending) Made-with: Cursor * parity: MSVC/clang hygiene #3515–#3519 #3521; triage batch - dup_filter_sink: filter_ const, const filter_duration (#3515) - logger: should_flush uses flush_level() (#3516) - daily_file_sink: new_filename locals (#3516) - spdlog::should_log(level log_level) (#3519) - example my_type value_ / ctor param (#3521) - Triage: PORTED 1774e700 309204d5 f2a9dec0 472945ba; N/A d299603e 57505989; SUPERSEDED 1ef8d3ce 8cfd4a7e; fix ba508057 row Made-with: Cursor * parity: udp_sink const udp_sink_config& (#3520); triage fc7e9c87 1685e694 - dist_sink already used std::move(sinks) - SUPERSEDED: no common-inl.h on v2; log_with_format_ avoids fmt copy path (#3541) Made-with: Cursor * parity: README fmt::format_to (#3259); triage 2670f47d d276069a 951c5b99 - Document ambiguous format_to fix in README user-defined type example - SUPERSEDED: z_formatter warning, fmt11 const formatter, rotate_now + test Made-with: Cursor * parity: lock rotate_now mutex (#3281); triage a2b42620 f355b3d5 d276069a - rotating_file_sink::rotate_now matches #3281 (sync with sink_it_) - SUPERSEDED: CMake 3.10..3.21 (v2 uses 3.23); daily test fmt::format; fmt11 const row Made-with: Cursor * parity: basic_file_sink::truncate (#3280); triage fwrite/fmt/test batch - truncate(): lock + file_helper::reopen(true) - test basic_file_sink_truncate - SUPERSEDED: b7e0e2c2 71925ca3 fa6605dc 885b5473 96c9a62b 1e6250e1 d7155530 Made-with: Cursor * parity: test_sink/callback iterator cast (#3315); triage Catch2 #3038 - difference_type cast for formatted.end() - eol_len (ad0f31c0) - SUPERSEDED: c1569a3d Catch2 v3.5.0, 73e2e02b wstr_to_utf8buf bounds Made-with: Cursor * parity: SPDLOG_WCHAR_CONSOLE WriteConsoleW path (#3092); triage b6da5944 - WIN32 option SPDLOG_WCHAR_CONSOLE; SPDLOG_UTF8_TO_WCHAR_CONSOLE in private defs - wincolor print_range_: utf8_to_wstrbuf + WriteConsoleW when defined - N/A: async_msg flush_callback move-assign (no v1 shape on v2) Made-with: Cursor * triage: v1 async_logger/thread_pool + fmt 11.1 batch (15 SHAs) - N/A: fe79bfcc 6725584e async tests 16e0d2e7 63d18842 d8e0ad46 1e7d7e07 3c23c27d - SUPERSEDED: faa0a7a9 85bdab0c 276ee5f5 7f8060d5 96a8f625 - Counts: 58 SUPERSEDED, 129 N/A, 17 PENDING; merge-report subsection Made-with: Cursor * Port v1 TSAN CMake (#3237); close 3A triage (MDC N/A, fmt 5A) Made-with: Cursor * docs(triage): note 3A table complete Made-with: Cursor * 5A: bundle fmt 12.1.0 (match v1.x), FMT_INSTALL, MSVC /wd4834, find_dependency(fmt 12) Made-with: Cursor * docs(5.4): migration and release notes for v1 parity integration branch Made-with: Cursor * docs: cross-link migration notes; refresh PRD/tasks/merge-report for completed 5A/3A Made-with: Cursor * revert: remove README and PRD cross-links to migration notes Made-with: Cursor * docs(merge-report): audit — add 9fe79692 to ports table; fix 6004e3d1 paths Made-with: Cursor * Remove tasks * PR comment fixes * Fix small random issues * Fix PR comments - un-remove the comment and allow any fmt library version --------- Co-authored-by: Jan Moravec <jan.moravec@hidglobal.com>
2026-04-08 16:17:37 +02:00
int value_ = 0;
explicit my_type(int value)
: value_(value) {}
2021-12-04 14:32:01 +02:00
};
template <>
struct fmt::formatter<my_type> : fmt::formatter<std::string> {
auto format(my_type my, format_context &ctx) const -> decltype(ctx.out()) {
Synchronize v2.x With Changes from v1.x (#3581) * docs(tasks): v1.x inventory, triage template, merge report; update task checklist - Record merge-base and export v1-only commits (v2..v1) - Document failed merge attempt: v2 file tree diverges from v1 - Mark completed checklist items 0.x, 1.x, merge report draft (5.2) Made-with: Cursor * fix(pattern): %z with UTC pattern time shows +00:00 (port v1 09a674b7) - z_formatter takes pattern_time_type; emit +00:00 when pattern uses UTC - Track port in tasks/commits-ported.txt and merge-report; update checklist Made-with: Cursor * fix(os): Windows utc_minutes_offset via mktime/_mkgmtime (port v1 b656d1ce) - Replace GetTimeZoneInformation-based offset with v1.x mktime/_mkgmtime approach - Add tests/test_timezone.cpp and extend pattern_formatter tests; update os.h comment Made-with: Cursor * test(timezone): POSIX TZ with DST rules; include fcntl in tcp_client_unix (v1 ports) - 0f7562a0: EST5EDT / IST-2IDT macros for POSIX vs Windows - d2100d5d: fcntl.h for Unix tcp client header (v2 path) Made-with: Cursor * feat(tcp): connect timeouts and socket IO timeouts; ci: checkout@v6 (v1 ports) - 9ecdf5c8: connect_socket_with_timeout on Unix/Windows; tcp_sink timeout_ms - 3c61b051: actions/checkout@v6 on all workflows - tcp_sink: remove duplicate #pragma once Made-with: Cursor * feat(dup_filter_sink): ctor with sink list (v1 45b67eee); add full v1 SHA triage table - tasks/v1-triage-complete.md: 245 commits PORTED/PENDING/N/A for PRD 3A tracking - Merge report and task checklist updated Made-with: Cursor * feat(level): case-insensitive level_from_str; cmake: BUILD_TYPE only if top-level (v1 ports) - 566b2d14: common.cpp + test_misc (SUPERSEDED note for d5af52d9 in triage) - dd3ca04a: guard default CMAKE_BUILD_TYPE for add_subdirectory consumers - Update v1-triage-complete.md counts and statuses Made-with: Cursor * v1 parity: MSVC UTF-8, ansicolor/syslog/os, getenv, triage docs - CMake: SPDLOG_MSVC_UTF8 + /utf-8 for real MSVC only - ansicolor: protected target_file_; fix set_color_mode_ lock nesting - os: drop redundant fileapi.h; spdlog::details::os::getenv via std::getenv - tests: stopwatch waits 500ms; includes/triage/commits-ported/merge-report updates - Reclassify superseded v1 SHAs (Sep, syslog, stopwatch ms, utf8 tests, etc.) Made-with: Cursor * parity: ringbuffer zero capacity, utf8 assert; v1 triage sync - ringbuffer_sink: throw if n_items==0 (#3436); test expects spdlog_ex - utf8_to_wstrbuf: assert compares int to static_cast<int>(target.size()) (#3479) - Triage: PORTED ad725d34 getenv, 677a2d93 stopwatch, 3f7e5028, a6215527; SUPERSEDED a45c9390, eeb22c13, 5673e9e5, fe4f9952, 287333ee - tasks: 27 PORTED / 26 SUPERSEDED / 78 PENDING; merge-report + commits-ported Made-with: Cursor * docs(tasks): note regular commits and push after parity ports Made-with: Cursor * parity: dup_filter_sink notification level from last duplicate (#3390) - Remove notification_level ctor arg; track skipped_msg_log_level_ on duplicate skips - Test: skipped summary line uses same short level as duplicated messages - Triage: 847db337 PORTED; 28/26/77 counts; merge-report + commits-ported Made-with: Cursor * parity: UWP getenv (WINAPI_FAMILY); triage fmt/cfg/no-except - os_windows: detect non-desktop/UWP for empty getenv (#3489) - Triage: PORTED 8806ca65; SUPERSEDED e3f5a4fe e655dbb6; N/A ae1de0dc 548b2642 - Counts 29/28/116/72; merge-report + commits-ported Made-with: Cursor * parity: qt_sinks sign casts (#3487); triage 9c582574 superseded - qt_color_sink: qsizetype for UTF-8 color range lengths; index colors_ with size_t - SUPERSEDED: 9c582574 — os_unix utc_minutes_offset already matches #3366 - Counts 30/29/70; merge-report + commits-ported Made-with: Cursor * parity: SPDLOG_NO_TZ_OFFSET (#3483); triage #3360 superseded - CMake: option SPDLOG_NO_TZ_OFFSET; PUBLIC compile definition when ON - z_formatter: +??:?? when macro; else keep UTC +00:00 and local offset - utc_minutes_offset: stub on Unix/Windows when macro - test_pattern_formatter: %z UTC case matches placeholder when NO_TZ - SUPERSEDED 10320184 (ScopedPadder / %D already in v2) - Triage 31/30/68; merge-report + commits-ported Made-with: Cursor * triage: supersede 5931a3d6 ba508057 47b7e7c7 (already on v2 tree) Made-with: Cursor * tasks: sync 5.1 triage counts (33 superseded, 65 pending) Made-with: Cursor * parity: MSVC/clang hygiene #3515–#3519 #3521; triage batch - dup_filter_sink: filter_ const, const filter_duration (#3515) - logger: should_flush uses flush_level() (#3516) - daily_file_sink: new_filename locals (#3516) - spdlog::should_log(level log_level) (#3519) - example my_type value_ / ctor param (#3521) - Triage: PORTED 1774e700 309204d5 f2a9dec0 472945ba; N/A d299603e 57505989; SUPERSEDED 1ef8d3ce 8cfd4a7e; fix ba508057 row Made-with: Cursor * parity: udp_sink const udp_sink_config& (#3520); triage fc7e9c87 1685e694 - dist_sink already used std::move(sinks) - SUPERSEDED: no common-inl.h on v2; log_with_format_ avoids fmt copy path (#3541) Made-with: Cursor * parity: README fmt::format_to (#3259); triage 2670f47d d276069a 951c5b99 - Document ambiguous format_to fix in README user-defined type example - SUPERSEDED: z_formatter warning, fmt11 const formatter, rotate_now + test Made-with: Cursor * parity: lock rotate_now mutex (#3281); triage a2b42620 f355b3d5 d276069a - rotating_file_sink::rotate_now matches #3281 (sync with sink_it_) - SUPERSEDED: CMake 3.10..3.21 (v2 uses 3.23); daily test fmt::format; fmt11 const row Made-with: Cursor * parity: basic_file_sink::truncate (#3280); triage fwrite/fmt/test batch - truncate(): lock + file_helper::reopen(true) - test basic_file_sink_truncate - SUPERSEDED: b7e0e2c2 71925ca3 fa6605dc 885b5473 96c9a62b 1e6250e1 d7155530 Made-with: Cursor * parity: test_sink/callback iterator cast (#3315); triage Catch2 #3038 - difference_type cast for formatted.end() - eol_len (ad0f31c0) - SUPERSEDED: c1569a3d Catch2 v3.5.0, 73e2e02b wstr_to_utf8buf bounds Made-with: Cursor * parity: SPDLOG_WCHAR_CONSOLE WriteConsoleW path (#3092); triage b6da5944 - WIN32 option SPDLOG_WCHAR_CONSOLE; SPDLOG_UTF8_TO_WCHAR_CONSOLE in private defs - wincolor print_range_: utf8_to_wstrbuf + WriteConsoleW when defined - N/A: async_msg flush_callback move-assign (no v1 shape on v2) Made-with: Cursor * triage: v1 async_logger/thread_pool + fmt 11.1 batch (15 SHAs) - N/A: fe79bfcc 6725584e async tests 16e0d2e7 63d18842 d8e0ad46 1e7d7e07 3c23c27d - SUPERSEDED: faa0a7a9 85bdab0c 276ee5f5 7f8060d5 96a8f625 - Counts: 58 SUPERSEDED, 129 N/A, 17 PENDING; merge-report subsection Made-with: Cursor * Port v1 TSAN CMake (#3237); close 3A triage (MDC N/A, fmt 5A) Made-with: Cursor * docs(triage): note 3A table complete Made-with: Cursor * 5A: bundle fmt 12.1.0 (match v1.x), FMT_INSTALL, MSVC /wd4834, find_dependency(fmt 12) Made-with: Cursor * docs(5.4): migration and release notes for v1 parity integration branch Made-with: Cursor * docs: cross-link migration notes; refresh PRD/tasks/merge-report for completed 5A/3A Made-with: Cursor * revert: remove README and PRD cross-links to migration notes Made-with: Cursor * docs(merge-report): audit — add 9fe79692 to ports table; fix 6004e3d1 paths Made-with: Cursor * Remove tasks * PR comment fixes * Fix small random issues * Fix PR comments - un-remove the comment and allow any fmt library version --------- Co-authored-by: Jan Moravec <jan.moravec@hidglobal.com>
2026-04-08 16:17:37 +02:00
return fmt::format_to(ctx.out(), "[my_type value={}]", my.value_);
2020-09-26 15:30:45 +03:00
}
};
2022-10-31 17:35:24 +02:00
void user_defined_example() { spdlog::info("user defined type: {}", my_type(14)); }
2020-09-26 15:30:45 +03:00
// Custom error handler. Will be triggered on log failure.
void err_handler_example() {
2020-09-26 15:30:45 +03:00
// can be set globally or per logger(logger->set_error_handler(..))
2024-01-13 18:20:08 +02:00
spdlog::set_error_handler([](const std::string &msg) { printf("*** Custom log error handler: %s ***\n", msg.c_str()); });
2020-09-26 15:30:45 +03:00
}
// syslog example (linux/osx/freebsd)
#ifndef _WIN32
#include "spdlog/sinks/syslog_sink.h"
void syslog_example() {
2020-09-26 15:30:45 +03:00
std::string ident = "spdlog-example";
auto syslog_logger = spdlog::create<syslog_sink_mt>("syslog", ident, LOG_PID);
2020-09-26 15:30:45 +03:00
syslog_logger->warn("This is warning that will end up in syslog.");
}
#endif
// Android example.
#if defined(__ANDROID__)
#include "spdlog/sinks/android_sink.h"
void android_example() {
2020-09-26 15:30:45 +03:00
std::string tag = "spdlog-android";
auto android_logger = spdlog::android_logger_mt("android", tag);
android_logger->critical("Use \"adb shell logcat\" to view this message.");
}
#endif
// Log patterns can contain custom flags.
// this will add custom flag '%*' which will be bound to a <my_formatter_flag> instance
#include "spdlog/pattern_formatter.h"
class my_formatter_flag : public spdlog::custom_flag_formatter {
2020-09-26 15:30:45 +03:00
public:
2024-01-13 09:37:32 +02:00
void format(const spdlog::details::log_msg &, const std::tm &, spdlog::memory_buf_t &dest) override {
2020-09-26 15:30:45 +03:00
std::string some_txt = "custom-flag";
dest.append(some_txt.data(), some_txt.data() + some_txt.size());
}
2024-11-30 13:05:12 +02:00
[[nodiscard]]
2024-12-01 23:59:09 +02:00
std::unique_ptr<custom_flag_formatter> clone() const override {
return std::make_unique<my_formatter_flag>();
}
2020-09-26 15:30:45 +03:00
};
void custom_flags_example() {
auto formatter = std::make_unique<spdlog::pattern_formatter>();
2020-09-26 15:30:45 +03:00
formatter->add_flag<my_formatter_flag>('*').set_pattern("[%n] [%*] [%^%l%$] %v");
// set the new formatter using spdlog::set_formatter(formatter) or
// logger->set_formatter(formatter) spdlog::set_formatter(std::move(formatter));
2021-11-15 14:32:34 +02:00
}
void file_events_example() {
// pass the spdlog::file_event_handlers to file sinks for open/close log file notifications
spdlog::file_event_handlers handlers;
2024-12-06 19:21:42 +02:00
handlers.before_open = [](spdlog::filename_t) { spdlog::trace("Before opening logfile"); };
handlers.after_open = [](spdlog::filename_t, std::FILE *fstream) {
2024-12-06 19:21:42 +02:00
spdlog::trace("After opening logfile");
2021-11-15 14:54:51 +02:00
fputs("After opening\n", fstream);
2021-11-15 14:32:34 +02:00
};
handlers.before_close = [](spdlog::filename_t, std::FILE *fstream) {
2024-12-06 19:21:42 +02:00
spdlog::trace("Before closing logfile");
2021-11-15 14:54:51 +02:00
fputs("Before closing\n", fstream);
2021-11-15 14:32:34 +02:00
};
2024-12-06 19:21:42 +02:00
handlers.after_close = [](spdlog::filename_t) { spdlog::trace("After closing logfile"); };
2024-01-13 09:37:32 +02:00
auto file_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>("logs/events-sample.txt", true, handlers);
2021-11-16 23:44:35 +02:00
spdlog::logger my_logger("some_logger", file_sink);
2024-12-06 19:21:42 +02:00
my_logger.trace("Some log line");
2020-09-26 15:30:45 +03:00
}
2024-12-06 19:21:42 +02:00
void replace_global_logger_example() {
// store the old logger so we don't break other examples.
2024-12-06 19:21:42 +02:00
auto old_logger = spdlog::global_logger();
auto new_logger = spdlog::create<basic_file_sink_mt>("new_global_logger", "logs/new-default-log.txt", true);
2024-12-06 19:21:42 +02:00
spdlog::set_global_logger(new_logger);
spdlog::set_level(spdlog::level::info);
spdlog::debug("This message should not be displayed!");
spdlog::set_level(spdlog::level::trace);
spdlog::debug("This message should be displayed..");
2024-12-06 19:21:42 +02:00
spdlog::set_global_logger(old_logger);
}