adding budgets and configs, have a more solid strategy now for allocation failures
This commit is contained in:
parent
be50fd9fea
commit
8f160b9426
|
|
@ -277,10 +277,16 @@ pub const Verbosity = enum(u8) {
|
|||
|
||||
var gLoggerSystem: LoggerSystem = undefined;
|
||||
|
||||
/// Producer allocations must be thread-safe, independently of the consumer arena.
|
||||
pub const LoggerSystemInitOptions = struct {
|
||||
payload_allocator_budget: usize = 4096, // in KiB, 4MB to start
|
||||
payload_allocator_overbudget_crash: usize = 4096, // in KiB, 4MB to start
|
||||
payload_overbudget: bool = false, // allow payload allocator to exceed budget, default: no
|
||||
|
||||
queue_capacity: usize = 1024,
|
||||
payload_allocator: std.mem.Allocator = std.heap.smp_allocator,
|
||||
|
||||
system_memory_budget: usize = 4096, // in KiB, 4MB to start
|
||||
allow_overbudget: bool = true, // otherwise crash if we exceed 4MB usage in the arena
|
||||
overbudget_crash: usize = 1024 * 1024, // 1GiB is absolute maximum.
|
||||
};
|
||||
|
||||
const PendingLog = struct {
|
||||
|
|
@ -328,7 +334,8 @@ pub const StructuredLogStats = struct {
|
|||
/// Keep at a stable address. Initialize before starting producers; close and
|
||||
/// join all producers before deinit/reinitialization. Only one thread may drain,
|
||||
/// inspect the registries/entries, render to stdout, or deinitialize the context.
|
||||
pub const LoggerSystem = struct {
|
||||
pub fn DeclareLoggerSystem(comptime opts: LoggerSystemInitOptions) type {
|
||||
return struct {
|
||||
stdout_buffer: [8192 * 8]u8 = undefined,
|
||||
stdout_file_writer: std.Io.File.Writer = undefined,
|
||||
stdout_writer: *std.Io.Writer = undefined,
|
||||
|
|
@ -354,7 +361,7 @@ pub const LoggerSystem = struct {
|
|||
stats: StructuredLogStats = .{},
|
||||
outputWriters: std.ArrayList(*std.Io.Writer) = .empty,
|
||||
|
||||
pub const EnqueueError = ArgsSerializer.Error || std.mem.Allocator.Error || error{ QueueFull, Closed };
|
||||
pub const options: LoggerSystemInitOptions = opts;
|
||||
|
||||
pub fn addStdout(self: *@This()) !void {
|
||||
try self.addWriter(self.stdout_writer);
|
||||
|
|
@ -367,7 +374,7 @@ pub const LoggerSystem = struct {
|
|||
/// Encodes using argument types only. No registry access or shared writer.
|
||||
/// On success, ownership of the payload transfers to the queue.
|
||||
/// Site/logger descriptors must outlive all queued and retained events.
|
||||
pub fn enqueueArgs(self: *@This(), site: *const LogSite, logger: *const LoggerState, verbosity: Verbosity, args: anytype) EnqueueError!void {
|
||||
pub fn enqueueArgs(self: *@This(), site: *const LogSite, logger: *const LoggerState, verbosity: Verbosity, args: anytype) !void {
|
||||
var writer: std.Io.Writer.Allocating = .init(self.payload_allocator);
|
||||
defer writer.deinit();
|
||||
|
||||
|
|
@ -388,7 +395,13 @@ pub const LoggerSystem = struct {
|
|||
const bytes = try writer.toOwnedSlice();
|
||||
errdefer self.payload_allocator.free(bytes);
|
||||
|
||||
const pending: PendingLog = .{ .site = site, .logger = logger, .verbosity = verbosity, .serialized_args = bytes, .usSinceStart = usSinceStart };
|
||||
const pending: PendingLog = .{
|
||||
.site = site,
|
||||
.logger = logger,
|
||||
.verbosity = verbosity,
|
||||
.serialized_args = bytes,
|
||||
.usSinceStart = usSinceStart,
|
||||
};
|
||||
if (try self.queue.putUncancelable(self.io, &.{pending}, 0) == 0) {
|
||||
_ = self.dropped.fetchAdd(1, .monotonic);
|
||||
return error.QueueFull;
|
||||
|
|
@ -479,18 +492,28 @@ pub const LoggerSystem = struct {
|
|||
self.queue.close(self.io);
|
||||
}
|
||||
|
||||
pub fn init(self: *@This(), io: std.Io, allocator: std.mem.Allocator) void {
|
||||
self.initOptions(io, allocator, .{});
|
||||
pub fn check(value: bool, comptime fmt: []const u8, args: anytype) void {
|
||||
if (value)
|
||||
return;
|
||||
|
||||
std.debug.print("PANIC!! " ++ fmt, args);
|
||||
@panic("Check failed");
|
||||
}
|
||||
|
||||
pub fn initOptions(self: *@This(), io: std.Io, allocator: std.mem.Allocator, options: LoggerSystemInitOptions) void {
|
||||
std.debug.assert(options.queue_capacity > 0);
|
||||
/// Producer allocations must be thread-safe, independently of the consumer arena.
|
||||
pub fn init(self: *@This(), io: std.Io, allocator: std.mem.Allocator, payload_allocator: std.mem.Allocator) void {
|
||||
check(options.queue_capacity >= 64, "queue capacity abnormally small {d}", .{options.queue_capacity});
|
||||
check(options.queue_capacity <= 10000, "queue capacity abnormally large {d}", .{options.queue_capacity});
|
||||
|
||||
self.* = .{};
|
||||
self.io = io;
|
||||
self.backing = allocator;
|
||||
self.payload_allocator = options.payload_allocator;
|
||||
self.payload_allocator = payload_allocator;
|
||||
self.arena = std.heap.ArenaAllocator.init(allocator);
|
||||
self.queue_buffer = allocator.alloc(PendingLog, options.queue_capacity) catch @panic("log queue oom");
|
||||
self.queue_buffer = allocator.alloc(PendingLog, options.queue_capacity) catch {
|
||||
std.debug.print("queue_buffer_alloc failed {d}", .{options.queue_capacity});
|
||||
@panic("Check failed");
|
||||
};
|
||||
self.queue = .init(self.queue_buffer);
|
||||
self.stdout_file_writer = .init(.stdout(), io, &self.stdout_buffer);
|
||||
self.stdout_writer = &self.stdout_file_writer.interface;
|
||||
|
|
@ -512,13 +535,12 @@ pub const LoggerSystem = struct {
|
|||
self.arena.deinit();
|
||||
}
|
||||
};
|
||||
|
||||
pub fn initialize(io: std.Io, allocator: std.mem.Allocator) void {
|
||||
gLoggerSystem.init(io, allocator);
|
||||
}
|
||||
|
||||
pub fn initializeOptions(io: std.Io, allocator: std.mem.Allocator, options: LoggerSystemInitOptions) void {
|
||||
gLoggerSystem.initOptions(io, allocator, options);
|
||||
pub const LoggerSystem = DeclareLoggerSystem(.{});
|
||||
|
||||
pub fn initialize(io: std.Io, allocator: std.mem.Allocator, payload_allocator: std.mem.Allocator) void {
|
||||
gLoggerSystem.init(io, allocator, payload_allocator);
|
||||
}
|
||||
|
||||
/// Counts rejected full-queue submissions (including retries) and events lost
|
||||
|
|
@ -544,7 +566,7 @@ pub fn drain() !usize {
|
|||
/// Consumer-thread checkpoint: drains up to one queue capacity and flushes
|
||||
/// stdout. Join producers first when a complete final flush is required.
|
||||
pub fn flush() void {
|
||||
_ = drain() catch @panic("log drain failed");
|
||||
_ = drain() catch return;
|
||||
gLoggerSystem.stdout_writer.flush() catch {};
|
||||
}
|
||||
|
||||
|
|
@ -628,7 +650,7 @@ pub const StructuredLog = struct {
|
|||
/// numbered arguments, escaped braces, scalar formats and constant options.
|
||||
/// Named/dynamic options and custom Zig format methods are unsupported.
|
||||
/// Integer schemas wider than 128 bits are unsupported.
|
||||
pub fn render(self: @This(), logger: *const LoggerSystem, writer: *std.Io.Writer, options: RenderOptions) RenderError!void {
|
||||
pub fn render(self: @This(), logger: anytype, writer: *std.Io.Writer, options: RenderOptions) RenderError!void {
|
||||
if (self.loggerId >= logger.loggerStatesById.items.len or self.sourceId >= logger.logSites.items.len) return error.InvalidLogReference;
|
||||
const site = logger.logSites.items[self.sourceId];
|
||||
const ops = site.decoder.ops;
|
||||
|
|
@ -936,7 +958,7 @@ pub fn DeclareLogger(comptime LoggerName: []const u8, comptime opts: LoggerOptio
|
|||
loggerState.verbosity.store(v, .monotonic);
|
||||
}
|
||||
|
||||
pub fn tryAddLog(comptime s: std.builtin.SourceLocation, v: Verbosity, comptime fmt: []const u8, args: anytype) LoggerSystem.EnqueueError!void {
|
||||
pub fn tryAddLog(comptime s: std.builtin.SourceLocation, v: Verbosity, comptime fmt: []const u8, args: anytype) !void {
|
||||
if (@backingInt(loggerState.verbosity.load(.monotonic)) > @backingInt(v)) return;
|
||||
|
||||
const FmtSite = struct {
|
||||
|
|
@ -949,7 +971,7 @@ pub fn DeclareLogger(comptime LoggerName: []const u8, comptime opts: LoggerOptio
|
|||
/// Drop new events when full; callers needing retries can use tryAddLog.
|
||||
pub fn addLog(comptime s: std.builtin.SourceLocation, v: Verbosity, comptime fmt: []const u8, args: anytype) void {
|
||||
tryAddLog(s, v, fmt, args) catch |err| switch (err) {
|
||||
error.QueueFull, error.Closed => {},
|
||||
error.QueueFull, error.Closed, error.OutOfMemory => {},
|
||||
else => @panic("log serialization failed"),
|
||||
};
|
||||
}
|
||||
|
|
@ -984,7 +1006,7 @@ test "structured logging end to end" {
|
|||
}.log;
|
||||
// Exercise static site reuse across independent system lifetimes.
|
||||
for (0..2) |_| {
|
||||
initializeOptions(std.testing.io, std.testing.allocator, .{ .queue_capacity = 1, .payload_allocator = std.testing.allocator });
|
||||
initialize(std.testing.io, std.testing.allocator, std.testing.allocator);
|
||||
defer deinit();
|
||||
Logger.setVerbosity(.warn);
|
||||
Logger.addLog(@src(), .log, "filtered", .{});
|
||||
|
|
@ -1008,6 +1030,11 @@ test "structured logging end to end" {
|
|||
try std.testing.expectEqualSlices(u8, &.{ 1, 0 }, bool_entry.serialized_args);
|
||||
try std.testing.expectEqual(@as(usize, 4), gLoggerSystem.logSites.items.len);
|
||||
try std.testing.expectEqual(@as(usize, 1), gLoggerSystem.loggerStatesById.items.len);
|
||||
|
||||
for (0..LoggerSystem.options.queue_capacity - 1) |x| {
|
||||
Logger.addLog(@src(), .warn, "queued {x}", .{x});
|
||||
}
|
||||
|
||||
Logger.addLog(@src(), .warn, "queued", .{});
|
||||
try std.testing.expectError(error.QueueFull, Logger.tryAddLog(@src(), .warn, "full", .{}));
|
||||
try std.testing.expectEqual(@as(u64, 1), droppedCount());
|
||||
|
|
@ -1049,7 +1076,7 @@ test "concurrent logging with bounded queue and simultaneous main thread drain"
|
|||
}
|
||||
}
|
||||
};
|
||||
gLoggerSystem.initOptions(std.testing.io, std.testing.allocator, .{ .queue_capacity = 8, .payload_allocator = std.testing.allocator });
|
||||
gLoggerSystem.init(std.testing.io, std.testing.allocator, std.testing.allocator);
|
||||
defer deinit();
|
||||
var start: std.Io.Event = .unset;
|
||||
var stop: std.atomic.Value(bool) = .init(false);
|
||||
|
|
@ -1114,7 +1141,7 @@ test "testing" {
|
|||
ending,
|
||||
};
|
||||
|
||||
initialize(std.testing.io, std.testing.allocator);
|
||||
initialize(std.testing.io, std.testing.allocator, std.testing.allocator);
|
||||
defer deinit();
|
||||
const Logger = DeclareLogger("mylogger", .{ .verbosity = .verbose });
|
||||
Logger.addLog(@src(), .log, "{} {} who doesn't {} {s} 2 + 2 is {d}", .{ TestEnum.ending, TestEnum2.ending, true, "dragons", 4 });
|
||||
|
|
|
|||
Loading…
Reference in New Issue