# Load the plugin into Dancer2 # see Log::Report::import() for %options use Dancer2::Plugin::LogReport %options; # Stop execution, redirect, and display an error to the user $name or error "Please enter a name"; # Add debug information to logger trace "We're here"; # Handling user errors cleanly if (process( sub {MyApp::Model->create_user} )) { # Success, redirect user elsewhere } else { # Failed, continue as if submit hadn't been made. # Error message will be in session for display later. } # Send errors to template for display hook before_template => sub { my $tokens = shift; $tokens->{messages} = session 'messages'; session 'messages' => []; }
[The Dancer2 plugin was contributed by Andrew Beverley]
This module provides easy access to the extensive logging facilities provided by Log::Report. Along with Dancer2::Logger::LogReport, this brings together all the internal Dancer2 logging, handling for expected and unexpected exceptions, translations and application logging.
Logging is extremely flexible using many of the available dispatchers. Multiple dispatchers can be used, each configured separately to display different messages in different formats. By default, messages are logged to a session variable for display on a webpage, and to STDERR.
Messages within this plugin use the extended manual Dancer2::Logger::LogReport::Message class rather than the standard Log::Report::Message class.
Note that it is currently recommended to use the plugin in all apps within
a Dancer2 program, not only some. Therefore, wherever you use Dancer2
you should also use Dancer2::Plugin::LogReport
. This does not apply if
using the same app name (use Dancer2 appname, 'Already::Exists'
). In
all other modules, you can just use Log::Report
.
Read the DETAILS in below in this manual-page.
This chapter will guide you through the myriad of ways that you can use Log::Report in your Dancer2 application.
We will set up our application to do the following:
In its simplest form, this module can be used for more flexible logging
get '/route' => sub { # Stop execution, redirect, and display an error to the user $name or error "Please enter a name";
# The same but translated $name or error __"Please enter a name"; # The same but translated and with variables $name or error __x"{name} is not valid", name => $name;
# Show the user a warning, but continue execution mistake "Not sure that's what you wanted";
# Add debug information, can be caught in syslog by adding # the (for instance) syslog dispatcher trace "Hello world"; };
To make full use of Log::Report, you'll need to use both Dancer2::Logger::LogReport and Dancer2::Plugin::LogReport.
Set up Dancer2::Logger::LogReport by adding it to your Dancer2 application configuration (see manual Dancer2::Config). By default, all messages will go to STDERR.
To get all message out "the Perl way" (using print, warn and die) just use
logger: "LogReport"
At start, these are handled by a Log::Report::Dispatcher::Perl object, named 'default'. If you open a new dispatcher with the name 'default', the output via the perl mechanisms will be stopped.
To also send messages to your syslog:
logger: "LogReport" engines: logger: LogReport: log_format: %a%i%m # See Dancer2::Logger::LogReport app_name: MyApp dispatchers: default: # Name type: SYSLOG # Log::Reporter::dispatcher() options identity: myapp facility: local0 flags: "pid ndelay nowait" mode: DEBUG
To send messages to a file:
logger: "LogReport" engines: logger: LogReport: log_format: %a%i%m # See Dancer2::Logger::LogReport app_name: MyApp dispatchers: logfile: # "default" dispatcher stays open as well type: FILE to: /var/log/myapp.log charset: utf-8 mode: DEBUG
See Log::Report::Dispatcher for full details of options.
Finally: a Dancer2 script may run many applications. Each application can have its own logger configuration. However, Log::Report dispatchers are global, so will be shared between Dancer2 applications. Any attempt to create a new Log::Report dispatcher by the same name (as will happen when a new Dancer2 application is started with the same configuration) will be ignored.
To use the plugin, you simply use it in your application:
package MyApp; use Log::Report (); # use early and minimal once use Dancer2; use Dancer2::Plugin::LogReport %config;
Dancer2::Plugin::LogReport takes the same %config
options as
Log::Report itself (see Log::Report::import()).
If you want to send messages from your modules/models, there is
no need to use this specific plugin. Instead, you should simply
use Log::Report
to negate the need of loading all the Dancer2
specific code.
In its simplest form, you can now use all the Log::Report logging functions to send messages to your dispatchers (as configured in the Logger configuration):
trace "I'm here"; warning "Something dodgy happened"; panic "I'm bailing out"; # Additional, special Dancer2 keyword success "Settings saved successfully";
Log::Report is a combination of a logger and an exception system. Messages to be logged are thrown to all listening dispatchers to be handled.
This module will also catch any unexpected exceptions:
# This will be caught, the error will be logged (full stacktrace to STDOUT, # short message to the session messages), and the user will be forwarded # (default to /). This would also be sent to syslog with the appropriate # dispatcher. get 'route' => sub { my $foo = 1; my $bar = $foo->{x}; # whoops }
For a production application (show_errors: 1
), the message saved in the
session will be the generic text "An unexpected error has occurred". This
can be customised in the configuration file, and will be translated.
To make it easier to send messages to your users, messages at the following
levels are also stored in the user's session: notice
, warning
, mistake
,
error
, fault
, alert
, failure
and panic
.
You can pass these to your template and display them at each page render:
hook before_template => sub { my $tokens = shift; $tokens->{messages} = session 'messages'; session 'messages' => []; # Clear the message queue }
Then in your template (for example the main layout):
[% FOR message IN messages %] <div class="alert alert-[% message.bootstrap_color %]"> [% message.toString | html_entity %] </div> [% END %]
The bootstrap_color
of the message is compatible with Bootstrap contextual
colors: success
, info
, warning
or danger
.
Now, anywhere in your application that you have used Log::Report, you can
warning "Hey user, you should now about this";
and the message will be sent to the next page the user sees.
Sometimes we write a function in a model, and it would be nice to have a nice easy way to return from the function with an error message. One way of doing this is with a separate error message variable, but that can be messy code. An alternative is to use exceptions, but these can be a pain to deal with in terms of catching them. Here's how to do it with Log::Report.
In this example, we do use exceptions, but in a neat, easier to use manner.
First, your module/model:
package MyApp::CD; sub update { my ($self, %values) = @_; $values{title} or error "Please enter a title"; $values{description} or warning "No description entered"; }
Then, in your controller:
package MyApp; use Dancer2; post '/cd' => sub { my %values = ( title => param('title'); description => param('description'); ); if (process sub { MyApp::CD->update(%values) } ) { success "CD updated successfully"; redirect '/cd'; } template 'cd' => { values => \%values }; }
Now, when update() is called, any exceptions are caught. However, there is
no need to worry about any error messages. Both the error and warning
messages in the above code will have been stored in the messages session
variable, where they can be displayed using the code in the previous section.
The error
will have caused the code to stop running, and process()
will have returned false. warning
will have simply logged the warning
and not caused the function to stop running.
If you use manual DBIx::Class in your application, you can easily integrate its logging and exceptions. To log SQL queries:
# Log all queries and execution time $schema->storage->debugobj(new Log::Report::DBIC::Profiler); $schema->storage->debug(1);
By default, exceptions from DBIC are classified at the level "error". This is normally a user level error, and thus may be filtered as normal program operation. If you do not expect to receive any DBIC exceptions, then it is better to class them at the level "panic":
# panic() DBIC errors $schema->exception_action(sub { panic @_ }); # Optionally get a stracktrace too $schema->stacktrace(1);
If you are occasionally running queries where you expect to naturally get exceptions (such as not inserting multiple values on a unique constraint), then you can catch these separately:
try { $self->schema->resultset('Unique')->create() }; # Log any messages from try block, but only as trace $@->reportAll(reason => 'TRACE');
If you have an unexpected exception in your production application, then you probably want to be notified about it. One way to do so is configure rsyslog to send emails of messages at the panic level. Use the following configuration to do so:
# Normal logging from LOCAL0 local0.* -/var/log/myapp.log # Load the mail module $ModLoad ommail # Configure sender, receiver and mail server $ActionMailSMTPServer localhost $ActionMailFrom root $ActionMailTo root # Set up an email template $template mailSubject,"Critical error on %hostname%" $template mailBody,"RSYSLOG Alert\r\nmsg='%msg%'\r\nseverity='%syslogseverity-text%'" $ActionMailSubject mailSubject # Send an email no more frequently than every minute $ActionExecOnlyOnceEveryInterval 60 # Configure the level of message to notify via email if $syslogfacility-text == 'local0' and $syslogseverity < 3 then :ommail:;mailBody $ActionExecOnlyOnceEveryInterval 0
With the above configuration, you will only be emailed of severe errors, but can view the full log information in /var/log/myapp.log