c_formatter assumed a fixed 24 character field, but the day of month is printed without padding, so dates on days 1-9 are 23 characters wide. E_formatter assumed a fixed 10 character field for a variable length number. scoped_padder sizes padding and truncation from that value, so padded output was too short and the ! truncation cut characters from the field (and from preceding output for %E).
Compute the real width from the printed values instead.
Co-authored-by: Gabi Melman <gmelman1@gmail.com>
Avoid reopening, truncating or deleting the current file when explicit
message timestamps are ahead of the wall clock. Cover append, truncate,
and one-file retention, including the following hourly rotation.
to12h() only subtracted 12 for hours above 12, so hour 0 stayed 0 and
%I printed "00" and %r "00:30:00 AM" during the first hour of the day.
The documented range of %I is 01-12, and strftime prints 12 there.
Co-authored-by: Michiel van Slobbe <michiel.van.slobbe@gmail.com>
Co-authored-by: Gabi Melman <gmelman1@gmail.com>
sd_journal_send returns a negative errno-style code without updating errno. Use the returned value when constructing the spdlog exception so failures report the actual cause.
WSAStartup and getaddrinfo return their error codes directly. Reading WSAGetLastError instead can report an unrelated or zero code. Pass the returned values to the Windows TCP sink error formatter.
FD_SET writes outside fd_set when a socket descriptor reaches FD_SETSIZE. Use poll for timed Unix connects and cover the high-descriptor case with a loopback regression test.
The raw-header-only consumer in tests/cmake/tweakme uses the installed
headers directly instead of linking a spdlog target, so it does not
inherit /utf-8. The bundled fmt then fails with MSVC:
error C2338: static_assert failed: 'Unicode support requires
compiling with /utf-8'
The Windows CI jobs only run spdlog-utests.exe, so spdlog-cmake-tweakme
was never exercised with MSVC there.
Co-authored-by: Leander Schulten <Leander.Schulten@tetys.de>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Gabi Melman <gmelman1@gmail.com>
A zero-capacity queue cannot accept the terminate message posted by the thread pool destructor, so destroying such a pool blocks forever. Reject the invalid capacity before starting worker threads and cover it with a regression test.
All loggers could be flushed automatically based on a duration, a log
level or manually, when having a reference already or via logger name using
get(const std::string &name).
By making details::registry::flush_all() publicly available, one might have
better control when the flush happens without knowing all logger names.
Co-authored-by: Gabi Melman <gmelman1@gmail.com>
These messages are useful, but only once, showing them again and again
and again as CMake reruns in the same build tree is more annoying than
anything else.
Skip doing this by defining a helper spdlog_message_once() function and
use it instead of message().
Co-authored-by: Gabi Melman <gmelman1@gmail.com>
* Add size accessors to basic_file_sink and rotating_file_sink
basic_file_sink gains size(), exposing the file size that file_helper
already tracked internally. rotating_file_sink gains get_current_size()
alongside its existing get_max_size()/get_max_files() accessors.
While adding get_current_size(), found that rotate_() never reset
current_size_ itself - only sink_it_ did so after calling it. This left
current_size_ stale after an explicit rotate_now() call until the next
write. Fixed by resetting current_size_ in rotate_() directly.
Added tests covering both new accessors, including rotate_now().
* Add test proving manual rotate_now() caused premature rotation
Directly demonstrates the bug fixed in the previous commit: without
resetting current_size_ inside rotate_(), a rotate_now() call left the
size counter stale, causing the next size check in sink_it_ to compare
against inflated values. This test writes well under max_size after a
manual rotation and asserts no further rotation occurs. Confirmed red on
the pre-fix code (a spurious second rotation happened after ~13 real
bytes against a max_size of 100) and green with the fix in place.
* Remove size() for basic_file_sink
* Removed redundant current_size_=0
---------
Co-authored-by: Claude <noreply@anthropic.com>
The daily_filename_calculator and hourly_filename_calculator produce
filenames using an underscore separator (e.g. basename_YYYY-MM-DD.ext
and basename_YYYY-MM-DD_HH.ext), but the surrounding comments described
the format with a dot separator (basename.YYYY-MM-DD.ext) and, for the
hourly sink, a dash before the hour. Update the comments to match the
actual output produced by calc_filename.
* Initial plan
* Pin windows workflow to windows-2022 for VS2022 generator
* Skip Coverity job when required secrets are unavailable
---------
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
* feat: add Grafana Loki sink
Adds a new sink that pushes log entries to Grafana Loki via its HTTP/1.1 push API.
Dependencies (header-only, consistent with mongo_sink/kafka_sink pattern):
- nlohmann/json for JSON serialization
- cpp-httplib for HTTP transport
include/spdlog/sinks/loki_sink.h:
- loki_sink_config: server_host/server_port required at construction; optional fields: labels, add_level_label, timeout_seconds (0 = cpp-httplib defaults; set to bound blocking time in sink_it_())
- loki_sink<Mutex> template with loki_sink_mt/st aliases
- Factory functions: loki_logger_mt/st (synchronous) and loki_logger_async_mt/st (async, recommended for production)
- Default pattern is "%v" (message text only) since timestamp and level go into Loki structured fields; override with set_pattern() as usual
- set_connection_timeout / set_read_timeout / set_write_timeout all honor timeout_seconds; HTTP 204 is the only accepted success status per Loki API
- Labels JSON pre-built in constructor; build_json_() is private const
* fix: use macros namespace definitions
* fix: do not enforce C++17 by using string_views
* fix: drop qualifiers from factory types
* feat: use keep_alive to prevent reopening the connection
* fix: do not overwrite user-provided level label when add_level_label is set
* fix: include HTTP status and response body in loki_sink error message
* fix: override set_pattern_ to preserve eol="" after set_pattern() calls
Setting the eol="" explicitly in override preserves generating malformed Loki lines caused by set_pattern() from the user
* fix: format description
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
* fix: rephrase comments to avoid direct TODOs
* docs: use more concrete Grafana reference in description
---------
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
* Remove redundant spdlog:: qualification inside namespace blocks
All spdlog:: references inside the spdlog namespace are already in scope
without qualification. Removing them prepares the headers for a future
change that allows the namespace to be customised: a custom namespace
definition would make these double-qualified names fail to resolve.
* Enable defining custom namespace for spdlog
* fixup! Remove redundant spdlog:: qualification inside namespace blocks
* fixup! Enable defining custom namespace for spdlog
* fixup! Enable defining custom namespace for spdlog
SPDLOG_NS__ used double underscores, making it a reserved identifier in
C++. SPDLOG_NAMESPACE is the name described in the PR description and is
a natural fit as the public-facing counterpart to SPDLOG_NAMESPACE_BEGIN.
* fixup! Enable defining custom namespace for spdlog
* fixup! Enable defining custom namespace for spdlog
Optional: show both the C++11/17 and the C++20 spelling of the
inline-namespace wrap, since C++20 users may still prefer the older
nested form for readability or consistency.
* fixup! Enable defining custom namespace for spdlog
* FIXMEUP Fix typo: skin_config → sink_config in udp_sink.h
Pre-existing upstream typo in the udp_logger_mt factory function.
Flagged by Copilot on PR #3610 review:
https://github.com/gabime/spdlog/pull/3610#discussion_r3346986667
To be moved to the start of the branch (before our changes) during the
final rebase.
* fixup! Enable defining custom namespace for spdlog
* Drop hard-coded spdlog:: prefix from exception messages
These messages are emitted from inside the namespace, which becomes
configurable via SPDLOG_NAMESPACE in this branch. Hard-coding "spdlog::"
in the text makes it misleading when the namespace is renamed, so drop
the prefix; the type name alone identifies the source.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* Add systemd_namespace_sink and related unit tests
Adds systemd_namespace_sink that can open a stream to a specific systemd
journal namespace for logging. This was created as a separate sink from
systemd_sink because it has significant difference due to systemd's
journal API: `sd_journal_send()` does not have namespace-specific
counterpart and thus this cannot utilize other extra journal fields than
`PRIORITY` (via kernel-style log level prefixes).
Another difference is that this API is only available from systemd
version 256, thus a version check was added to CMake file for the unit
tests so that they are not automatically included if `libsystemd` is not
new enough.
Unit tests are split to two parts: first one runs always and it just
uses the stream to log to default namespace (should always work). Second
one requires manual setting up of "custom" journal namespace and thus is
ignored from the default set of tests (can be run by specifying
`[systemd_namespace]` tag explicitly when running tests). On the other
hand, the second part also automatically checks the output correctness
from journal.
* Fixes and optimizations
`SD_JOURNAL_SUPPRESS_LOCATION` is not needed by this sink since it does
not use the APIs that add the location info.
Moved level prefixes to `static constexpr` to indicate those being
compile-time constants (and also saves a bit space).
Removed message length truncation since with this stream API we don't
even know the maximum length of the messages. Journald truncates the
message at its end based on its own configuration.
Added error checking to `fwrite_bytes()` calls similarly to other sinks.
Optimized away excess `\n` check.
Added `flush_()` implementation.
* Error handling fixes and change write_or_throw to class method
* string_view_t for level prefix
* Clean up log level prefix writing
The CI was passing -DCMAKE_CXX_STANDARD=11 even when SPDLOG_USE_STD_FORMAT=ON,
which requires C++20. Previously this was masked because CMakeLists.txt
unconditionally set C++20 for std::format, but #3583 made that conditional.
Why? to be able to use a greater c++ when using conan.
Because conan reports: Warning: Standard CMAKE_CXX_STANDARD value defined in conan_toolchain.cmake to 23 has been modified to 20 by .conan2/p/b/spdlo815dcec129526/b/src/CMakeLists.txt
POSIX 2024 defines three formats for the TZ environment variable,
1. Implementation defined format which always starts with a colon:
":characters".
2. A specifier which fully describes the timezone rule in format
"stdoffset[dst[offset][,start[/time],end[/time]]]". Note the
offset and start/end part could be omitted, in which case one hour
is implied, or it's considered implementation-defined when changing
to and from Daylight Saving Time occurs.
3. Geographical or special timezone from an implementation-defined
timezone database.
POSIX 2024 requires the format 1 and 2 to take precedence over format 3.
In tests/test_timezone.cpp, we set TZ to "EST5EDT" or "IST-2IDT".
According to POSIX, "EST5EDT" should be interpreted as
- timezone "EST", which is five hours behind UTC
- corresponding DST timezone is "EDT", which is one hour ahead of
standard time
- it's implementation-defined when changing to and from DST occurs
The interpretion is similar for TZ="IST-2IDT". Obviously we're hitting
implementation-defined behavior here, which is inconsistent across
platforms, e.g., musl considers DST is always active if both DST start
and end rules are omitted, thus test_timezone.cpp would fail.
Let's also provide DST rules when setting TZ variables to avoid
depending on implementation-defined behavior.
Fixes: b656d1ceec ("Windows utc_minutes_offset(): Fix historical DST accuracy and improve offset calculation speed (~2.5x) (#3508)")
Signed-off-by: Yao Zi <me@ziyao.cc>
Modified from_str() to perform case-insensitive comparison for all level names.
This allows environment variables and SPDLOG_LEVEL_NAMES to use uppercase or
mixed case level names (e.g., DEBUG, INFO, Warning) while maintaining full
backward compatibility with existing lowercase names.