1=encoding utf8
2
3=head1 NAME
4
5Dancer2::Plugin::LogReport - logging and exceptions via Log::Report
6
7=head1 INHERITANCE
8
9 Dancer2::Plugin::LogReport
10   is a Dancer2::Plugin
11
12=head1 SYNOPSIS
13
14  # Load the plugin into Dancer2
15  # see Log::Report::import() for %options
16  use Dancer2::Plugin::LogReport %options;
17
18  # Stop execution, redirect, and display an error to the user
19  $name or error "Please enter a name";
20
21  # Add debug information to logger
22  trace "We're here";
23
24  # Handling user errors cleanly
25  if (process( sub {MyApp::Model->create_user} )) {
26      # Success, redirect user elsewhere
27  } else {
28      # Failed, continue as if submit hadn't been made.
29      # Error message will be in session for display later.
30  }
31
32  # Send errors to template for display
33  hook before_template => sub {
34      my $tokens = shift;
35      $tokens->{messages} = session 'messages';
36      session 'messages' => [];
37  }
38
39=head1 DESCRIPTION
40
41[The Dancer2 plugin was contributed by Andrew Beverley]
42
43This module provides easy access to the extensive logging facilities
44provided by L<Log::Report|Log::Report>. Along with L<Dancer2::Logger::LogReport|Dancer2::Logger::LogReport>,
45this brings together all the internal Dancer2 logging, handling for
46expected and unexpected exceptions, translations and application logging.
47
48Logging is extremely flexible using many of the available
49L<dispatchers|Log::Report::Dispatcher/DETAILS>.  Multiple dispatchers can be
50used, each configured separately to display different messages in different
51formats.  By default, messages are logged to a session variable for display on
52a webpage, and to STDERR.
53
54Messages within this plugin use the extended
55L<Dancer2::Logger::LogReport::Message> class rather than the standard
56L<Log::Report::Message> class.
57
58Note that it is currently recommended to use the plugin in all apps within
59a Dancer2 program, not only some. Therefore, wherever you C<use Dancer2>
60you should also C<use Dancer2::Plugin::LogReport>. This does not apply if
61using the same app name (C<use Dancer2 appname, 'Already::Exists'>). In
62all other modules, you can just C<use Log::Report>.
63
64Read the L</DETAILS> in below in this manual-page.
65
66=head1 METHODS
67
68=over 4
69
70=item $obj-E<gt>B<fatal_handler>()
71
72C<fatal_handler()> allows alternative handlers to be defined in place of (or in
73addition to) the default redirect handler that is called on a fatal error.
74
75Calls should be made with 1 parameter: the subroutine to call in the case of a
76fatal error. The subroutine is passed 3 parameters: the DSL, the message in
77question, and the reason. The subroutine should return true or false depending
78on whether it handled the error. If it returns false, the next fatal handler is
79called, and if there are no others then the default redirect fatal handler is
80called.
81
82example: Error handler based on URL (e.g. API)
83
84  fatal_handler sub {
85    my ($dsl, $msg, $reason) = @_;
86    return if $dsl->app->request->uri !~ m!^/api/!;
87    status $reason eq 'PANIC' ? 'Internal Server Error' : 'Bad Request';
88    $dsl->send_as(JSON => {
89        error             => 1,
90        error_description => $msg->toString,
91    }, {
92        content_type => 'application/json; charset=UTF-8',
93    });
94  };
95
96example: Return JSON responses for requests with content-type of application/json
97
98fatal_handler sub {
99    my ($dsl, $msg, $reason, $default) = @_;
100
101    (my $ctype = $dsl->request->header('content-type')) =~ s/;.*//;
102    return if $ctype ne 'application/json';
103    status $reason eq 'PANIC' ? 'Internal Server Error' : 'Bad Request';
104    $dsl->send_as(JSON => {
105        error       => 1,
106        description => $msg->toString,
107    }, {
108        content_type => 'application/json; charset=UTF-8',
109    });
110  };
111
112=item $obj-E<gt>B<process>()
113
114C<process()> is an eval, but one which expects and understands exceptions
115generated by L<Log::Report|Log::Report>. Any messages will be logged as normal in
116accordance with the dispatchers, but any fatal exceptions will be caught
117and handled gracefully.  This allows much simpler error handling, rather
118than needing to test for lots of different scenarios.
119
120In a module, it is enough to simply use the C<error> keyword in the event
121of a fatal error.
122
123The return value will be 1 for success or 0 if a fatal exception occurred.
124
125See the L</DETAILS> for an example of how this is expected to be used.
126
127This module is configured only once in your application. The other modules
128which make your website do not need to require this plugin, instead they
129can C<use Log::Report> to get useful functions like error and fault.
130
131=back
132
133=head2 Handlers
134
135All the standard L<Log::Report|Log::Report> functions are available to use. Please see the
136L<Log::Report/"The Reason for the report"> for details
137of when each one should be used.
138
139L<Log::Report class functionality|Log::Report::Message.pod#class-STRING-ARRAY>
140to class messages (which can then be tested later):
141
142  notice __x"Class me up", _class => 'label';
143  ...
144  if ($msg->inClass('label')) ...
145
146L<Dancer2::Plugin::LogReport|Dancer2::Plugin::LogReport> has a special message class, C<no_session>,
147which prevents the message from being saved to the messages session
148variable. This is useful, for example, if you are writing messages within
149the session hooks, in which case recursive loops can be experienced.
150
151=over 4
152
153=item $obj-E<gt>B<alert>()
154
155=item $obj-E<gt>B<assert>()
156
157=item $obj-E<gt>B<error>()
158
159=item $obj-E<gt>B<failure>()
160
161=item $obj-E<gt>B<fault>()
162
163=item $obj-E<gt>B<info>()
164
165=item $obj-E<gt>B<mistake>()
166
167=item $obj-E<gt>B<notice>()
168
169=item $obj-E<gt>B<panic>()
170
171=item $obj-E<gt>B<success>()
172
173This is a special additional type, equivalent to C<notice>.  The difference is
174that messages using this keyword will have the class C<success> added, which
175can be used to color the messages differently to the end user. For example,
176L<Dancer2::Plugin::LogReport::Message#bootstrap_color> uses this to display the
177message in green.
178
179=item $obj-E<gt>B<trace>()
180
181=item $obj-E<gt>B<warning>()
182
183=back
184
185=head1 DETAILS
186
187This chapter will guide you through the myriad of ways that you can use
188L<Log::Report|Log::Report> in your Dancer2 application.
189
190We will set up our application to do the following:
191
192=over 4
193
194=item Messages to the user
195
196We'll look at an easy way to output messages to the user's web page, whether
197they be informational messages, warnings or errors.
198
199=item Debug information
200
201We'll look at an easy way to log debug information, at different levels.
202
203=item Manage unexpected exceptions
204
205We'll handle unexpected exceptions cleanly, in the unfortunate event that
206they happen in your production application.
207
208=item Email alerts of significant errors
209
210If we do get unexpected errors then we want to be notified them.
211
212=item Log DBIC information and errors
213
214We'll specifically look at nice ways to log SQL queries and errors when
215using DBIx::Class.
216
217=back
218
219=head2 Larger example
220
221In its simplest form, this module can be used for more flexible logging
222
223  get '/route' => sub {
224      # Stop execution, redirect, and display an error to the user
225      $name or error "Please enter a name";
226
227      # The same but translated
228      $name or error __"Please enter a name";
229
230      # The same but translated and with variables
231      $name or error __x"{name} is not valid", name => $name;
232
233      # Show the user a warning, but continue execution
234      mistake "Not sure that's what you wanted";
235
236      # Add debug information, can be caught in syslog by adding
237      # the (for instance) syslog dispatcher
238      trace "Hello world";
239   };
240
241=head2 Setup and Configuration
242
243To make full use of L<Log::Report>, you'll need to use both
244L<Dancer2::Logger::LogReport> and L<Dancer2::Plugin::LogReport>.
245
246=head3 Dancer2::Logger::LogReport
247
248Set up L<Dancer2::Logger::LogReport> by adding it to your Dancer2
249application configuration (see L<Dancer2::Config>). By default,
250all messages will go to STDERR.
251
252To get all message out "the Perl way" (using print, warn and die) just use
253
254  logger: "LogReport"
255
256At start, these are handled by a L<Log::Report::Dispatcher::Perl|Log::Report::Dispatcher::Perl> object,
257named 'default'.  If you open a new dispatcher with the name 'default',
258the output via the perl mechanisms will be stopped.
259
260To also send messages to your syslog:
261
262  logger: "LogReport"
263
264  engines:
265    logger:
266      LogReport:
267        log_format: %a%i%m      # See Dancer2::Logger::LogReport
268        app_name: MyApp
269        dispatchers:
270          default:              # Name
271            type: SYSLOG        # Log::Reporter::dispatcher() options
272            identity: myapp
273            facility: local0
274            flags: "pid ndelay nowait"
275            mode: DEBUG
276
277To send messages to a file:
278
279  logger: "LogReport"
280
281  engines:
282    logger:
283      LogReport:
284        log_format: %a%i%m      # See Dancer2::Logger::LogReport
285        app_name: MyApp
286        dispatchers:
287          logfile:              # "default" dispatcher stays open as well
288            type: FILE
289            to: /var/log/myapp.log
290            charset: utf-8
291            mode: DEBUG
292
293See L<Log::Report::Dispatcher> for full details of options.
294
295Finally: a Dancer2 script may run many applications.  Each application
296can have its own logger configuration.  However, Log::Report dispatchers
297are global, so will be shared between Dancer2 applications.  Any attempt
298to create a new Log::Report dispatcher by the same name (as will happen
299when a new Dancer2 application is started with the same configuration)
300will be ignored.
301
302=head3 Dancer2::Plugin::LogReport
303
304To use the plugin, you simply use it in your application:
305
306  package MyApp;
307  use Log::Report ();  # use early and minimal once
308  use Dancer2;
309  use Dancer2::Plugin::LogReport %config;
310
311Dancer2::Plugin::LogReport takes the same C<%config> options as
312L<Log::Report> itself (see L<Log::Report::import()|Log::Report/"Configuration">).
313
314If you want to send messages from your modules/models, there is
315no need to use this specific plugin. Instead, you should simply
316C<use Log::Report> to negate the need of loading all the Dancer2
317specific code.
318
319=head2 In use
320
321=head3 Logging debug information
322
323In its simplest form, you can now use all the
324L<Log::Report logging functions|Log::Report#The-Reason-for-the-report>
325to send messages to your dispatchers (as configured in the Logger
326configuration):
327
328  trace "I'm here";
329
330  warning "Something dodgy happened";
331
332  panic "I'm bailing out";
333
334  # Additional, special Dancer2 keyword
335  success "Settings saved successfully";
336
337=head3 Exceptions
338
339Log::Report is a combination of a logger and an exception system.  Messages
340to be logged are I<thrown> to all listening dispatchers to be handled.
341
342This module will also catch any unexpected exceptions:
343
344  # This will be caught, the error will be logged (full stacktrace to STDOUT,
345  # short message to the session messages), and the user will be forwarded
346  # (default to /). This would also be sent to syslog with the appropriate
347  # dispatcher.
348  get 'route' => sub {
349      my $foo = 1;
350      my $bar = $foo->{x}; # whoops
351  }
352
353For a production application (C<show_errors: 1>), the message saved in the
354session will be the generic text "An unexpected error has occurred". This
355can be customised in the configuration file, and will be translated.
356
357=head3 Sending messages to the user
358
359To make it easier to send messages to your users, messages at the following
360levels are also stored in the user's session: C<notice>, C<warning>, C<mistake>,
361C<error>, C<fault>, C<alert>, C<failure> and C<panic>.
362
363You can pass these to your template and display them at each page render:
364
365  hook before_template => sub {
366    my $tokens = shift;
367    $tokens->{messages} = session 'messages';
368    session 'messages' => []; # Clear the message queue
369  }
370
371Then in your template (for example the main layout):
372
373  [% FOR message IN messages %]
374    <div class="alert alert-[% message.bootstrap_color %]">
375      [% message.toString | html_entity %]
376    </div>
377  [% END %]
378
379The C<bootstrap_color> of the message is compatible with Bootstrap contextual
380colors: C<success>, C<info>, C<warning> or C<danger>.
381
382Now, anywhere in your application that you have used Log::Report, you can
383
384  warning "Hey user, you should now about this";
385
386and the message will be sent to the next page the user sees.
387
388=head3 Handling user errors
389
390Sometimes we write a function in a model, and it would be nice to have a
391nice easy way to return from the function with an error message. One
392way of doing this is with a separate error message variable, but that
393can be messy code. An alternative is to use exceptions, but these
394can be a pain to deal with in terms of catching them.
395Here's how to do it with Log::Report.
396
397In this example, we do use exceptions, but in a neat, easier to use manner.
398
399First, your module/model:
400
401  package MyApp::CD;
402
403  sub update {
404    my ($self, %values) = @_;
405    $values{title} or error "Please enter a title";
406    $values{description} or warning "No description entered";
407  }
408
409Then, in your controller:
410
411  package MyApp;
412  use Dancer2;
413
414  post '/cd' => sub {
415    my %values = (
416      title       => param('title');
417      description => param('description');
418    );
419    if (process sub { MyApp::CD->update(%values) } ) {
420      success "CD updated successfully";
421      redirect '/cd';
422    }
423
424    template 'cd' => { values => \%values };
425  }
426
427Now, when update() is called, any exceptions are caught. However, there is
428no need to worry about any error messages. Both the error and warning
429messages in the above code will have been stored in the messages session
430variable, where they can be displayed using the code in the previous section.
431The C<error> will have caused the code to stop running, and process()
432will have returned false. C<warning> will have simply logged the warning
433and not caused the function to stop running.
434
435=head3 Logging DBIC database queries and errors
436
437If you use L<DBIx::Class> in your application, you can easily integrate
438its logging and exceptions. To log SQL queries:
439
440  # Log all queries and execution time
441  $schema->storage->debugobj(new Log::Report::DBIC::Profiler);
442  $schema->storage->debug(1);
443
444By default, exceptions from DBIC are classified at the level "error". This
445is normally a user level error, and thus may be filtered as normal program
446operation. If you do not expect to receive any DBIC exceptions, then it
447is better to class them at the level "panic":
448
449  # panic() DBIC errors
450  $schema->exception_action(sub { panic @_ });
451  # Optionally get a stracktrace too
452  $schema->stacktrace(1);
453
454If you are occasionally running queries where you expect to naturally
455get exceptions (such as not inserting multiple values on a unique constraint),
456then you can catch these separately:
457
458  try { $self->schema->resultset('Unique')->create() };
459  # Log any messages from try block, but only as trace
460  $@->reportAll(reason => 'TRACE');
461
462=head3 Email alerts of exceptions
463
464If you have an unexpected exception in your production application,
465then you probably want to be notified about it. One way to do so is
466configure rsyslog to send emails of messages at the panic level. Use
467the following configuration to do so:
468
469  # Normal logging from LOCAL0
470  local0.*                        -/var/log/myapp.log
471
472  # Load the mail module
473  $ModLoad ommail
474  # Configure sender, receiver and mail server
475  $ActionMailSMTPServer localhost
476  $ActionMailFrom root
477  $ActionMailTo root
478  # Set up an email template
479  $template mailSubject,"Critical error on %hostname%"
480  $template mailBody,"RSYSLOG Alert\r\nmsg='%msg%'\r\nseverity='%syslogseverity-text%'"
481  $ActionMailSubject mailSubject
482  # Send an email no more frequently than every minute
483  $ActionExecOnlyOnceEveryInterval 60
484  # Configure the level of message to notify via email
485  if $syslogfacility-text == 'local0' and $syslogseverity < 3 then :ommail:;mailBody
486  $ActionExecOnlyOnceEveryInterval 0
487
488With the above configuration, you will only be emailed of severe errors, but can
489view the full log information in /var/log/myapp.log
490
491=head1 CONFIGURATION
492
493All configuration is optional. The example configuration file below shows the
494configuration options and defaults.
495
496    plugins:
497      LogReport:
498        # Whether to handle Dancer HTTP errors such as 404s. Currently has
499        # no effect due to unresolved issues saving messages to the session
500        # and accessing the DSL at that time.
501        handle_http_errors: 1
502        # Where to forward users in the event of an uncaught fatal
503        # error within a GET request
504        forward_url: /
505        # Or you can specify a template instead [1.13]
506        forward_template: error_template_file   # Defaults to empty
507        # For a production server (show_errors: 0), this is the text that
508        # will be displayed instead of unexpected exception errors
509        fatal_error_message: An unexpected error has occurred
510        # The levels of messages that will be saved to the session, and
511        # thus displayed to the end user
512        session_messages: [ NOTICE, WARNING, MISTAKE, ERROR, FAULT, ALERT, FAILURE, PANIC ]
513
514=head1 SEE ALSO
515
516This module is part of Log-Report distribution version 1.33,
517built on July 17, 2021. Website: F<http://perl.overmeer.net/CPAN/>
518
519=head1 LICENSE
520
521Copyrights 2007-2021 by [Mark Overmeer <markov@cpan.org>]. For other contributors see ChangeLog.
522
523This program is free software; you can redistribute it and/or modify it
524under the same terms as Perl itself.
525See F<http://dev.perl.org/licenses/>
526
527