Colorize request method in log output

This commit is contained in:
Bob Farrell 2024-01-18 22:03:35 +00:00
parent cb52ccffb9
commit b66073955d
4 changed files with 19 additions and 8 deletions

View File

@ -6,9 +6,8 @@ const Data = jetzig.data.Data;
const View = jetzig.views.View;
pub fn index(request: *Request, data: *Data) anyerror!View {
_ = request;
var object = try data.object();
try object.put("foo", data.string("hello"));
return error.OhNo;
// return request.render(.ok);
// return error.OhNo;
return request.render(.ok);
}

View File

@ -95,9 +95,9 @@ pub fn duration(allocator: std.mem.Allocator, delta: i64) ![]const u8 {
var buf: [1024]u8 = undefined;
const formatted_duration = try std.fmt.bufPrint(&buf, "{}", .{std.fmt.fmtDurationSigned(delta)});
if (delta < 100000) {
if (delta < 1000000) {
return try runtimeGreen(allocator, formatted_duration);
} else if (delta < 500000) {
} else if (delta < 5000000) {
return try runtimeYellow(allocator, formatted_duration);
} else {
return try runtimeRed(allocator, formatted_duration);

View File

@ -126,6 +126,18 @@ pub fn hash(self: *Self) ![]const u8 {
);
}
pub fn fmtMethod(self: *Self) []const u8 {
return switch (self.method) {
.GET => jetzig.colors.cyan("GET"),
.PUT => jetzig.colors.yellow("PUT"),
.PATCH => jetzig.colors.yellow("PATCH"),
.HEAD => jetzig.colors.white("HEAD"),
.POST => jetzig.colors.green("POST"),
.DELETE => jetzig.colors.red("DELETE"),
inline else => |method| jetzig.colors.white(@tagName(method)),
};
}
pub fn resourceModifier(self: *Self) ?Modifier {
const basename = std.fs.path.basename(self.segments.items[self.segments.items.len - 1]);
const extension = std.fs.path.extension(basename);

View File

@ -234,10 +234,10 @@ fn requestLogMessage(self: *Self, request: *jetzig.http.Request, result: jetzig.
const formatted_duration = try jetzig.colors.duration(self.allocator, self.duration());
defer self.allocator.free(formatted_duration);
return try std.fmt.allocPrint(self.allocator, "[{s} {s}] {s} {s}", .{
status.format(),
return try std.fmt.allocPrint(self.allocator, "[{s}/{s}/{s}] {s}", .{
formatted_duration,
@tagName(request.method),
request.fmtMethod(),
status.format(),
request.path,
});
}