| 1 | const std = @import("std"); |
| 2 | const tracer = @import("./mod.zig"); |
| 3 | const alloc = std.heap.c_allocator; |
| 4 | const log = std.log.scoped(.tracer); |
| 5 | const root = @import("root"); |
| 6 | const nfs = @import("nfs"); |
| 7 | const nio = @import("nio"); |
| 8 | const time = @import("time"); |
| 9 | const linux = @import("sys-linux"); |
| 10 | |
| 11 | var pid: linux.pid_t = undefined; |
| 12 | threadlocal var tid: linux.pid_t = undefined; |
| 13 | threadlocal var path: [:0]const u8 = undefined; |
| 14 | threadlocal var file: nfs.File = undefined; |
| 15 | threadlocal var buffered_writer: nio.BufferedWriter(4096, nfs.File) = undefined; |
| 16 | |
| 17 | pub fn init(args: struct {}) !void { |
| 18 | _ = args; |
| 19 | pid = linux.getpid(); |
| 20 | } |
| 21 | |
| 22 | pub fn deinit() void { |
| 23 | // |
| 24 | } |
| 25 | |
| 26 | pub fn init_thread(args: struct { nfs.Dir }) !void { |
| 27 | const dir = args[0]; |
| 28 | tid = linux.gettid(); |
| 29 | |
| 30 | path = try nio.fmt.allocPrintZ(alloc, "trace.{d}.{d}.chrome.json", .{ pid, tid }); |
| 31 | file = try dir.createFile(path, .{}); |
| 32 | buffered_writer = .init(file); |
| 33 | |
| 34 | try buffered_writer.writeAll("[\n"); |
| 35 | } |
| 36 | |
| 37 | pub fn deinit_thread() void { |
| 38 | defer alloc.free(path); |
| 39 | defer file.close(); |
| 40 | |
| 41 | buffered_writer.writeAll("]\n") catch {}; |
| 42 | buffered_writer.flush() catch {}; |
| 43 | } |
| 44 | |
| 45 | pub fn trace_begin(src: std.builtin.SourceLocation, comptime ifmt: []const u8, iargs: anytype) void { |
| 46 | buffered_writer.print( |
| 47 | \\{{"cat":"function", "name":"{s}:{d}:{d} ({s}) |
| 48 | ++ ifmt ++ |
| 49 | \\", "ph": "B", "pid": {d}, "tid": {d}, "ts": {d}}}, |
| 50 | \\ |
| 51 | , |
| 52 | .{ |
| 53 | src.file, |
| 54 | src.line, |
| 55 | src.column, |
| 56 | src.fn_name, |
| 57 | } ++ iargs ++ .{ |
| 58 | pid, |
| 59 | tid, |
| 60 | time.microTimestamp(), |
| 61 | }, |
| 62 | ) catch {}; |
| 63 | } |
| 64 | |
| 65 | pub fn trace_end(ctx: tracer.Ctx) void { |
| 66 | _ = ctx; |
| 67 | buffered_writer.print( |
| 68 | \\{{"cat":"function", "ph": "E", "pid": {d}, "tid": {d}, "ts": {d}}}, |
| 69 | \\ |
| 70 | , |
| 71 | .{ |
| 72 | pid, |
| 73 | tid, |
| 74 | time.microTimestamp(), |
| 75 | }, |
| 76 | ) catch {}; |
| 77 | } |
| 78 | |
| 79 | pub const Data = void; |