Something went wrong. Try again.
A Zig library for writing structured log messages directly to the systemd journal over its native datagram socket.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112// SPDX-FileCopyrightText: © 2024 Jeffrey C. Ollie <jeff@ocjtech.us>//// SPDX-License-Identifier: MIT
//! Routing `std.log` to the journal.//!//! Zig's logging goes wherever `std.Options.logFn` sends it, which by default//! is a line of text on stderr. Pointing it at journalz instead means the//! level becomes a real syslog priority that `journalctl -p` can select on,//! and the scope becomes a field that `journalctl LOG_SCOPE=http` can query,//! rather than both being prefixes in a string somebody has to grep.//!//! Run it and look://!//! journalctl --identifier=journalz-example --output=json-pretty//! journalctl --identifier=journalz-example LOG_SCOPE=database
const std = @import("std");const journalz = @import("journalz");
pub const std_options: std.Options = .{ // Otherwise `std.log.debug` is compiled out of a release build and the // journal never sees it. .log_level = .debug, .logFn = logToJournal,};
/// `logFn` is a free function with nowhere to put a logger, so it has to find/// one. It is read from every thread that logs, so it is set once before any/// of them start and left alone after that.var journal: ?journalz.Logger = null;
fn logToJournal( comptime level: std.log.Level, comptime scope: @EnumLiteral(), comptime format: []const u8, args: anytype,) void { const logger = journal orelse { // Anything logged before `main` has opened the journal, or after it // has closed it, still has somewhere to go. return std.log.defaultLog(level, scope, format, args); };
send(logger, level, scope, format, args) catch { // The journal is where diagnostics go, so a failure to reach it // cannot be reported by logging. Fall back to stderr rather than // dropping the message. std.log.defaultLog(level, scope, format, args); };}
fn send( logger: journalz.Logger, comptime level: std.log.Level, comptime scope: @EnumLiteral(), comptime format: []const u8, args: anytype,) !void { // std.log's four levels onto syslog's eight. The three journalz leaves // unused here -- EMERG, ALERT and CRIT -- are available to a program that // wants to raise something above `err`, by building the message itself. const priority: journalz.Priority = switch (level) { .err => .ERROR, .warn => .WARNING, .info => .INFO, .debug => .DEBUG, };
const msg = try logger.message(priority); errdefer msg.cancel();
var buf: [4096]u8 = undefined; var w = msg.writer(&buf);
try w.print("MESSAGE", format, args);
// The scope is a field of its own rather than a prefix on the message, // which is the whole reason to do this: journald indexes it, so // `journalctl LOG_SCOPE=database` selects on it. if (scope != .default) try w.writeAll("LOG_SCOPE", @tagName(scope));
try w.flush(); try msg.send();}
const database = std.log.scoped(.database);const http = std.log.scoped(.http);
pub fn main() !void { // `debug_io` is a singleton, separate from whatever `Io` the program // itself runs on. That is what makes it usable here: `logFn` is called // from anywhere, including from code that is in the middle of driving the // application's own `Io`, and logging should not reach back into that. journal = try .init(std.Options.debug_io, "journalz-example", .LOCAL4); defer { const logger = journal.?; journal = null; logger.deinit(); }
std.log.err("could not open {s}", .{"/etc/nonexistent"}); std.log.warn("retrying in {d} seconds", .{5}); std.log.info("listening on port {d}", .{8080}); std.log.debug("cache holds {d} entries", .{1024});
database.info("connected to {s}", .{"postgres://localhost/app"}); database.warn("query took {d}ms", .{2500});
http.info("{s} {s} {d}", .{ "GET", "/healthz", 200 });}