Debian Codegraph @

lib/Dancer2/Core/Role/Logger.pm

raw
1 package Dancer2::Core::Role::Logger;
2 # ABSTRACT: Role for logger engines
3 $Dancer2::Core::Role::Logger::VERSION = '2.2.2';
4 use Dancer2::Core::Types;
5
6 use Moo::Role;
7 use POSIX 'strftime';
8 use Encode ();
9 use Data::Dumper;
10
11 with 'Dancer2::Core::Role::Engine';
12
13 sub hook_aliases { +{} }
14 sub supported_hooks {
15 qw(
16 engine.logger.before
17 engine.logger.after
18 );
19 }
20
21 sub _build_type {'Logger'}
22
23 # This is the only method to implement by logger engines.
24 # It receives the following arguments:
25 # $msg_level, $msg_content, it gets called only if the configuration allows
26 # a message of the given level to be logged.
27 requires 'log';
28
29 has auto_encoding_charset => (
30 is => 'ro',
31 isa => Str,
32 );
33
34 has app_name => (
35 is => 'ro',
36 isa => Str,
37 default => sub {'-'},
38 );
39
40 has log_format => (
41 is => 'rw',
42 isa => Str,
43 default => sub {'[%a:%P] %L @%T> %m in %f l. %l'},
44 );
45
46 has caller_stack_size => (
47 is => 'rw',
48 isa => Int,
49 default => sub { 9; },
50 );
51
52 my $_levels = {
53
54 # levels < 0 are for core only
55 core => -10,
56
57 # levels > 0 are for end-users only
58 debug => 1,
59 info => 2,
60 warn => 3,
61 warning => 3,
62 error => 4,
63 };
64
65 has log_level => (
66 is => 'rw',
67 isa => Enum[keys %{$_levels}],
68 default => sub {'debug'},
69 );
70
71 sub _should {
72 my ( $self, $msg_level ) = @_;
73 my $conf_level = $self->log_level;
74 return $_levels->{$conf_level} <= $_levels->{$msg_level};
75 }
76
77 sub format_message {
78 my ( $self, $level, $message ) = @_;
79 chomp $message;
80
81 $message = Encode::encode( $self->auto_encoding_charset, $message )
82 if $self->auto_encoding_charset;
83
84 my $request = $self->request;
85 my $config = $self->config;
86
87 my $block_handler = sub {
88 my ( $block, $type ) = @_;
89 if ( $type eq 't' ) {
90 return POSIX::strftime( $block, localtime(time) );
91 }
92 elsif ( $type eq 'h' ) {
93 return ( $request && $request->header($block) ) || '-';
94 }
95 else {
96 Carp::carp("{$block}$type not supported");
97 return "-";
98 }
99 };
100
101 my $chars_mapping = $self->map_chars_to_subs($level, $message, );
102
103 my $char_mapping = sub {
104 my $char = shift;
105
106 my $cb = $chars_mapping->{$char};
107 if ( !$cb ) {
108 Carp::carp "%$char not supported.";
109 return "-";
110 }
111 $cb->($char);
112 };
113
114 my $fmt = $self->log_format;
115
116 $fmt =~ s/
117 (?:
118 \%\{(.+?)\}([a-z])|
119 \%([a-zA-Z])
120 )
121 / $1 ? $block_handler->($1, $2) : $char_mapping->($3) /egx;
122
123 return $fmt . "\n";
124 }
125
126 sub map_chars_to_subs {
127 my ( $self, $level, $message, $caller_delta ) = @_;
128 my @stack = caller($self->caller_stack_size + ($caller_delta // 0));
129 my $request = $self->request;
130 return {
131 a => sub { $self->app_name },
132 t => sub { POSIX::strftime( "%d/%b/%Y %H:%M:%S", localtime(time) ) },
133 T => sub { POSIX::strftime( "%Y-%m-%d %H:%M:%S", localtime(time) ) },
134 u => sub { POSIX::strftime( "%d/%b/%Y %H:%M:%S", gmtime(time) ) },
135 U => sub { POSIX::strftime( "%Y-%m-%d %H:%M:%S", gmtime(time) ) },
136 P => sub {$$},
137 L => sub {$level},
138 m => sub {$message},
139 p => sub { $stack[0] || '-' }, # package
140 f => sub { $stack[1] || '-' }, # filepath
141 l => sub { $stack[2] || '-' }, # line number
142 h => sub {
143 ( $request && ( $request->remote_host || $request->address ) ) || '-'
144 },
145 i => sub { ( $request && $request->id ) || '-' },
146 };
147 };
148
149 sub _serialize {
150 my @vars = @_;
151
152 return join q{}, map +(
153 ref $_
154 ? Data::Dumper->new( [$_] )->Terse(1)->Purity(1)->Indent(0)
155 ->Sortkeys(1)->Dump()
156 : ( defined($_) ? $_ : 'undef' )
157 ), @vars;
158 }
159
160 around 'log' => sub {
161 my ($orig, $self, @args) = @_;
162
163 $self->execute_hook( 'engine.logger.before', $self, @args );
164 $self->$orig( @args );
165 $self->execute_hook( 'engine.logger.after', $self, @args );
166 };
167
168 sub core {
169 my ( $self, @args ) = @_;
170 $self->_should('core') and $self->log( 'core', _serialize(@args) );
171 }
172
173 sub debug {
174 my ( $self, @args ) = @_;
175 $self->_should('debug') and $self->log( 'debug', _serialize(@args) );
176 }
177
178 sub info {
179 my ( $self, @args ) = @_;
180 $self->_should('info') and $self->log( 'info', _serialize(@args) );
181 }
182
183 sub warning {
184 my ( $self, @args ) = @_;
185 $self->_should('warning') and $self->log( 'warning', _serialize(@args) );
186 }
187
188 sub error {
189 my ( $self, @args ) = @_;
190 $self->_should('error') and $self->log( 'error', _serialize(@args) );
191 }
192
193 1;
194
195 __END__
196
197 =pod
198
199 =encoding UTF-8
200
201 =head1 NAME
202
203 Dancer2::Core::Role::Logger - Role for logger engines
204
205 =head1 VERSION
206
207 version 2.2.2
208
209 =head1 DESCRIPTION
210
211 Any class that consumes this role will be able to implement to write log messages.
212
213 In order to implement this role, the consumer B<must> implement the C<log>
214 method. This method will receives as argument the C<level> and the C<message>.
215
216 =head1 ATTRIBUTES
217
218 =head2 auto_encoding_charset
219
220 Charset to use when writing a message.
221
222 =head2 app_name
223
224 Name of the application. Can be used in the message.
225
226 =head2 log_format
227
228 This is a format string (or a preset name) to specify the log format.
229
230 The possible values are:
231
232 =over 4
233
234 =item %a
235
236 app name
237
238 =item %h
239
240 host emitting the request
241
242 =item %t
243
244 date (local timezone, formatted like %d/%b/%Y %H:%M:%S)
245
246 =item %T
247
248 date (local timezone, formatted like %Y-%m-%d %H:%M:%S)
249
250 =item %u
251
252 date (UTC timezone, formatted like %d/%b/%Y %H:%M:%S)
253
254 =item %U
255
256 date (UTC timezone, formatted like %Y-%m-%d %H:%M:%S)
257
258 =item %P
259
260 PID
261
262 =item %L
263
264 log level
265
266 =item %m
267
268 message
269
270 =item %p
271
272 package name that emits the message
273
274 =item %f
275
276 file name that emits the message
277
278 =item %l
279
280 line from the file
281
282 =item %i
283
284 request ID
285
286 =item %{$fmt}t
287
288 timer formatted with a valid time format
289
290 =item %{header}h
291
292 header value
293
294 =back
295
296 A format character that is not in the list above (whether mistyped or simply
297 unsupported) is not fatal: it produces a C<Carp> warning of the form
298 C<< %X not supported. >> and the field renders as C<->, leaving the rest of
299 the log line intact.
300
301 =head2 log_level
302
303 Level to use by default.
304
305 =head1 METHODS
306
307 =head2 core
308
309 Log messages as B<core>.
310
311 =head2 debug
312
313 Log messages as B<debug>.
314
315 =head2 info
316
317 Log messages as B<info>.
318
319 =head2 warning
320
321 Log messages as B<warning>.
322
323 =head2 error
324
325 Log messages as B<error>.
326
327 =head2 format_message
328
329 Provides a common message formatting.
330
331 =head2 map_chars_to_subs
332
333 Returns a hashref which has all the items needed for message formatting.
334
335 =head1 CONFIGURATION
336
337 The B<logger> configuration variable tells Dancer2 which engine to use.
338
339 You can change it either in your config.yml file:
340
341 # logging to console
342 logger: "console"
343
344 The log format can also be configured,
345 please see L<Dancer2::Core::Role::Logger/"log_format"> for details.
346
347 =head1 AUTHOR
348
349 Dancer Core Developers
350
351 =head1 COPYRIGHT AND LICENSE
352
353 This software is copyright (c) 2026 by Alexis Sukrieh.
354
355 This is free software; you can redistribute it and/or modify it under
356 the same terms as the Perl 5 programming language system itself.
357
358 =cut