Single-header structured logger in C
Find a file
2025-09-30 16:57:07 -06:00
slog update examples, msg last if source added 2025-09-30 16:57:07 -06:00
tests update examples, msg last if source added 2025-09-30 16:57:07 -06:00
.clang-format logger 2025-09-29 17:37:59 -06:00
.gitignore logger 2025-09-29 17:37:59 -06:00
CMakeLists.txt test 2025-09-29 17:51:36 -06:00
README.md update examples, msg last if source added 2025-09-30 16:57:07 -06:00

slog

Single-header structured logger in C99

Simple usage

  ...
	struct SlogLogger logger = SLOG_DEFAULT_TEXT_LOGGER;

	SLOG_DEBUG(&logger, "will not appear");
	// Dropped, the default text logger has .Opts.MinLevel = SlogLevelInfo

	SLOG_INFO(&logger, "hello from minimal.c");
	// The default text logger's output file is stdout:
	// time=2025-09-30T16:54:25.254250393-06:00 level=INFO msg=hello from minimal.c

	struct SlogAttr attrs[] = {
		SlogAttrB("ok", true),
	};

	SLOG_INFO_ATTRS(&logger, "hello", attrs);
	// time=2025-09-30T16:54:25.254327934-06:00 level=INFO msg=hello ok=true
  ...

Advanced usage

#include <slog/slog.h>
#include <stdbool.h>

int main(void)
{
	struct SlogHandlerOpts opts1 = {
		.File = stdout,
		.MinLevel = SlogLevelDebug,
		.Prefix = NULL,
		.AddSource = true,
		.Json = false,
	};

	struct SlogLogger l1 = {
		SlogTextHandler,
		opts1,
	};

	struct SlogHandlerOpts opts2 = {
		.File = stderr,
		.MinLevel = SlogLevelError,
		.Prefix = "scope",
		.AddSource = false,
		.Json = true,
	};

	struct SlogLogger l2 = {
		SlogTextHandler,
		opts2,
	};

	struct SlogAttr attrs[] = {
		SlogAttrB("ok", true),
	};

	SLOG_INFO_ATTRS(&l1, "hello", attrs);
	// stdout:
	// time=2025-09-30T16:54:25.251770492-06:00 level=INFO source=tests/slog.c:36 func=main msg=hello ok=true

	SLOG_ERROR(&l2, "hello");
	// stderr:
	// time=2025-09-30T16:54:25.251826602-06:00 level=ERROR msg=hello

	l1.Handler(&l1, SlogLevelWarn + 1, "my message", NULL, 0, NULL);
	// stdout:
	// time=2025-09-30T16:54:25.251831572-06:00 level=WARN+1 msg=my message

	return 0;
}