Add a logging allocator that uses std.log (#8511)
This commit is contained in:
@@ -599,4 +599,50 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
|
||||
\\emergency(c):
|
||||
\\
|
||||
);
|
||||
|
||||
// It is required to override the log function in order to print to stdout instead of stderr
|
||||
cases.add("std.heap.LoggingAllocator logs to std.log",
|
||||
\\const std = @import("std");
|
||||
\\
|
||||
\\pub const log_level: std.log.Level = .debug;
|
||||
\\
|
||||
\\pub fn main() !void {
|
||||
\\ var allocator_buf: [10]u8 = undefined;
|
||||
\\ var fixedBufferAllocator = std.mem.validationWrap(std.heap.FixedBufferAllocator.init(&allocator_buf));
|
||||
\\ const allocator = &std.heap.loggingAllocator(&fixedBufferAllocator.allocator).allocator;
|
||||
\\
|
||||
\\ var a = try allocator.alloc(u8, 10);
|
||||
\\ a = allocator.shrink(a, 5);
|
||||
\\ try std.testing.expect(a.len == 5);
|
||||
\\ try std.testing.expectError(error.OutOfMemory, allocator.resize(a, 20));
|
||||
\\ allocator.free(a);
|
||||
\\}
|
||||
\\
|
||||
\\pub fn log(
|
||||
\\ comptime level: std.log.Level,
|
||||
\\ comptime scope: @TypeOf(.EnumLiteral),
|
||||
\\ comptime format: []const u8,
|
||||
\\ args: anytype,
|
||||
\\) void {
|
||||
\\ const level_txt = switch (level) {
|
||||
\\ .emerg => "emergency",
|
||||
\\ .alert => "alert",
|
||||
\\ .crit => "critical",
|
||||
\\ .err => "error",
|
||||
\\ .warn => "warning",
|
||||
\\ .notice => "notice",
|
||||
\\ .info => "info",
|
||||
\\ .debug => "debug",
|
||||
\\ };
|
||||
\\ const prefix2 = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "): ";
|
||||
\\ const stdout = std.io.getStdOut().writer();
|
||||
\\ nosuspend stdout.print(level_txt ++ prefix2 ++ format ++ "\n", args) catch return;
|
||||
\\}
|
||||
,
|
||||
\\debug: alloc - success - len: 10, ptr_align: 1, len_align: 0
|
||||
\\debug: shrink - success - 10 to 5, len_align: 0, buf_align: 1
|
||||
\\critical: expand - failure: OutOfMemory - 5 to 20, len_align: 0, buf_align: 1
|
||||
\\debug: free - success - len: 5
|
||||
\\
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user