Knarr/RequestLog.pm

filter: Statementstmt 69.4% 50 / 72 Branchbran 42.3% 11 / 26 Conditioncond 14.2% 1 / 7 MC/DCmcdc 0.0% 0 / 4 Subroutinesub 81.2% 13 / 16 Podpod 100% 2 / 2 totaltotal 60.6% 77 / 127 CC 17 SCAR 23.5
CC
17
Cov
59%
_write_file
42.0
end_request
6.9
_build__enabled
3.7
CRAP 10.5
« Knarr/Tracing.pm ↑ Summary Knarr/Config.pm »
1 package Langertha::Knarr::RequestLog;
2 2 our $VERSION = '1.100';
3 # ABSTRACT: Local disk logging of proxy requests
4 2 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use Time::HiRes qw( gettimeofday tv_interval );
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use JSON::MaybeXS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
7 2 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 2 ▶use Log::Any qw( $log );
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10  
11 2 has config => (
12 is => 'ro',
13 required => 1,
14 );
15  
16  
17 2 has log_file => (
18 is => 'lazy',
19 builder => '_build_log_file',
20 );
21  
22 sub _build_log_file {
23 1 ▶ my ($self) = @_;
Subroutine _build_log_file: called CC=1 SCAR=0.0
24 1 return $self->config->log_file;
25 }
26  
27  
28 2 has log_dir => (
29 is => 'lazy',
30 builder => '_build_log_dir',
31 );
32  
33 sub _build_log_dir {
34 1 ▶ my ($self) = @_;
Subroutine _build_log_dir: called CC=1 SCAR=0.0
35 1 return $self->config->log_dir;
36 }
37  
38  
39 2 has _enabled => (
40 is => 'lazy',
41 builder => '_build__enabled',
42 );
43  
44 sub _build__enabled {
45 1 ▶ my ($self) = @_;
Subroutine _build__enabled: called CC=3 SCAR=13.1
46 1 ▶ return ($self->log_file || $self->log_dir) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->log_file || $self->log_dir ? : 1 0 1
Condition33%1/3
$self->log_file or $self->log_dir
l!l&&r!l&&!r
100
MC/DC0%0/2
$self->log_file or $self->log_dir
$self->log_file $self->log_dir
Truth table33%1/3
A or B
A= $self->log_fileB= $self->log_dir
ABresult
1X1
011
000
47 }
48  
49 2 has _json => (
50 is => 'lazy',
51 builder => '_build__json',
52 );
53  
54 sub _build__json {
55 1 ▶ return JSON::MaybeXS->new(utf8 => 1, convert_blessed => 1);
Subroutine _build__json: called CC=1 SCAR=0.0
56 }
57  
58 2 has _json_pretty => (
59 is => 'lazy',
60 builder => '_build__json_pretty',
61 );
62  
63 sub _build__json_pretty {
64 0 ▶ return JSON::MaybeXS->new(utf8 => 1, convert_blessed => 1, pretty => 1, canonical => 1);
Subroutine _build__json_pretty: not called CC=1 SCAR=6.9
65 }
66  
67 sub _timestamp {
68 2 ▶ my ($s, $us) = gettimeofday;
Subroutine _timestamp: called CC=1 SCAR=0.0
69 2 my @t = gmtime($s);
70 2 return sprintf("%04d-%02d-%02dT%02d:%02d:%02d.%03dZ",
71 $t[5]+1900, $t[4]+1, $t[3], $t[2], $t[1], $t[0], int($us/1000));
72 }
73  
74 sub _file_timestamp {
75 0 ▶ my ($s, $us) = gettimeofday;
Subroutine _file_timestamp: not called CC=1 SCAR=6.9
76 0 my @t = gmtime($s);
77 0 return sprintf("%04d%02d%02d_%02d%02d%02d_%03d",
78 $t[5]+1900, $t[4]+1, $t[3], $t[2], $t[1], $t[0], int($us/1000));
79 }
80  
81  
82 sub start_request {
83 2 ▶ my ($self, %opts) = @_;
Subroutine start_request: called CC=3 SCAR=11.1
Pod documented
84 2 ▶ return undef unless $self->_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_enabled 0 2 2
85  
86 return {
87 timestamp => _timestamp(),
88 t0 => [gettimeofday],
89 model => $opts{model},
90 format => $opts{format},
91 engine => $opts{engine},
92 path => $opts{path},
93 stream => $opts{stream} ? \1 : \0,
94 messages => $opts{messages},
95 params => $opts{params},
96 2 ▶ };
Branch: 1 branch
BranchTrueFalseTotal
$opts{'stream'} ? : 1 1 2
97 }
98  
99  
100 sub end_request {
101 2 ▶ my ($self, $handle, %opts) = @_;
Subroutine end_request: called CC=6 SCAR=19.3
Pod documented
102 2 ▶ return unless $self->_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_enabled 0 2 2
103 2 ▶ return unless $handle;
Branch: 1 branch
BranchTrueFalseTotal
unless $handle 0 2 2
104  
105 2 my $duration_ms = int(tv_interval($handle->{t0}) * 1000);
106  
107 my $entry = {
108 timestamp => $handle->{timestamp},
109 model => $handle->{model},
110 format => $handle->{format},
111 engine => $handle->{engine},
112 path => $handle->{path},
113 stream => $handle->{stream},
114 messages => $handle->{messages},
115 params => $handle->{params},
116 output => $opts{output},
117 usage => $opts{usage},
118 duration_ms => $duration_ms,
119 status => $opts{error} ? 'error' : 'ok',
120 error => $opts{error},
121 2 ▶ };
Branch: 1 branch
BranchTrueFalseTotal
$opts{'error'} ? : 0 2 2
122  
123 2 ▶ $self->_write_jsonl($entry) if $self->log_file;
Branch: 1 branch
BranchTrueFalseTotal
if $self->log_file 2 0 2
124 2 ▶ $self->_write_file($entry, $handle) if $self->log_dir;
Branch: 1 branch
BranchTrueFalseTotal
if $self->log_dir 0 2 2
125 }
126  
127 sub _write_jsonl {
128 2 ▶ my ($self, $entry) = @_;
Subroutine _write_jsonl: called CC=3 SCAR=11.4
129 2 eval {
130 2 ▶ open my $fh, '>>', $self->log_file
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">>", $self->log_file or die 'Cannot open log file ' . $self->log_file . ": $!" 0 2 2
131 or die "Cannot open log file " . $self->log_file . ": $!";
132 2 flock($fh, 2); # LOCK_EX
133 2 print $fh $self->_json->encode($entry) . "\n";
134 2 close $fh;
135 };
136 2 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 2 2
137 0 $log->warnf("RequestLog write error: %s", $@);
138 }
139 }
140  
141 sub _write_file {
142 0 ▶ my ($self, $entry, $handle) = @_;
Subroutine _write_file: not called CC=6 SCAR=37.4
143 0 eval {
144 0 my $dir = $self->log_dir;
145 0 ▶ unless (-d $dir) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-d $dir) 0 0 0
146 0 require File::Path;
147 0 File::Path::make_path($dir);
148 }
149  
150 0 ▶ my $model = $handle->{model} // 'unknown';
Condition0%0/2
$handle->{"model"} // "unknown"
l!l
00
MC/DC0%0/1
$handle->{"model"} // "unknown"
$handle->{"model"}
Truth table0%0/2
A
A= $handle->{"model"}
Aresult
11
00
151 0 ▶ my $format = $handle->{format} // 'unknown';
Condition0%0/2
$handle->{"format"} // "unknown"
l!l
00
MC/DC0%0/1
$handle->{"format"} // "unknown"
$handle->{"format"}
Truth table0%0/2
A
A= $handle->{"format"}
Aresult
11
00
152 # Sanitize for filename
153 0 $model =~ s/[^a-zA-Z0-9._-]/_/g;
154 0 $format =~ s/[^a-zA-Z0-9._-]/_/g;
155  
156 0 my $filename = _file_timestamp() . "_${format}_${model}.json";
157 0 my $path = File::Spec->catfile($dir, $filename);
158  
159 0 ▶ open my $fh, '>', $path
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">", $path or die "Cannot write log file ${path}: $!" 0 0 0
160 or die "Cannot write log file $path: $!";
161 0 print $fh $self->_json_pretty->encode($entry);
162 0 close $fh;
163 };
164 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
165 0 $log->warnf("RequestLog file write error: %s", $@);
166 }
167 }
168  
169  
170 2 1;
171  
172 __END__
173  
174 =pod
175  
176 =encoding UTF-8
177  
178 =head1 NAME
179  
180 Langertha::Knarr::RequestLog - Local disk logging of proxy requests
181  
182 =head1 VERSION
183  
184 version 1.100
185  
186 =head1 SYNOPSIS
187  
188 use Langertha::Knarr::RequestLog;
189  
190 my $rlog = Langertha::Knarr::RequestLog->new(config => $config);
191  
192 my $handle = $rlog->start_request(
193 model => 'gpt-4o',
194 format => 'openai',
195 engine => 'Langertha::Engine::OpenAI',
196 path => '/v1/chat/completions',
197 stream => 1,
198 messages => \@messages,
199 params => \%params,
200 );
201  
202 # ... handle request ...
203  
204 $rlog->end_request($handle,
205 output => $response_text,
206 usage => { input => 100, output => 50, total => 150 },
207 );
208  
209 =head1 DESCRIPTION
210  
211 Records every proxy request as a JSON log entry on local disk. Supports two
212 modes: JSONL (one line per request, append to a single file) and per-request
213 JSON files in a directory.
214  
215 When both C<log_file> and C<log_dir> are set, both are written. When neither
216 is set, all methods are no-ops.
217  
218 Log file/directory are read from the config file's C<logging:> section or
219 from the C<KNARR_LOG_FILE> and C<KNARR_LOG_DIR> environment variables. The
220 module strips surrounding quotes from environment variable values.
221  
222 =head2 config
223  
224 The L<Langertha::Knarr::Config> object. Required. Provides C<log_file> and
225 C<log_dir> settings.
226  
227 =head2 log_file
228  
229 Path to the JSONL log file. One JSON object per line, suitable for
230 C<tail -f knarr.jsonl | jq>. Resolved from C<logging.file> in config or
231 C<KNARR_LOG_FILE> environment variable.
232  
233 =head2 log_dir
234  
235 Path to a directory for per-request JSON files. Each request produces a
236 pretty-printed C<{timestamp}_{format}_{model}.json> file. Resolved from
237 C<logging.dir> in config or C<KNARR_LOG_DIR> environment variable.
238  
239 =head2 start_request
240  
241 my $handle = $rlog->start_request(
242 model => $model_name,
243 format => 'openai',
244 engine => $engine_class,
245 path => '/v1/chat/completions',
246 stream => 1,
247 messages => \@messages,
248 params => \%params,
249 );
250  
251 Begins collecting data for a request. Returns a handle (hashref) that must
252 be passed to L</end_request>. Returns C<undef> when logging is disabled.
253  
254 =head2 end_request
255  
256 $rlog->end_request($handle,
257 output => $response_text,
258 usage => { input => 100, output => 50, total => 150 },
259 );
260  
261 # On error:
262 $rlog->end_request($handle, error => "Something went wrong");
263  
264 Completes the log entry with output, usage, duration and writes it to disk.
265 Does nothing when C<$handle> is C<undef> (logging was disabled at start).
266  
267 =head1 SEE ALSO
268  
269 =over
270  
271 =item * L<Langertha::Knarr> — Request logging is wired in for all routes
272  
273 =item * L<Langertha::Knarr::Config> — Provides C<log_file> and C<log_dir>
274  
275 =item * L<Langertha::Knarr::Tracing> — Langfuse tracing (complementary)
276  
277 =back
278  
279 =head1 SUPPORT
280  
281 =head2 Issues
282  
283 Please report bugs and feature requests on GitHub at
284 L<https://github.com/Getty/langertha-knarr/issues>.
285  
286 =head2 IRC
287  
288 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
289  
290 =head1 CONTRIBUTING
291  
292 Contributions are welcome! Please fork the repository and submit a pull request.
293  
294 =head1 AUTHOR
295  
296 Torsten Raudssus <torsten@raudssus.de> L<https://raudssus.de/>
297  
298 =head1 COPYRIGHT AND LICENSE
299  
300 This software is copyright (c) 2026 by Torsten Raudssus.
301  
302 This is free software; you can redistribute it and/or modify it under
303 the same terms as the Perl 5 programming language system itself.
304  
305 =cut
« Knarr/Tracing.pm ↑ Summary Knarr/Config.pm »