.\" Automatically generated by Pod::Man 4.14 (Pod::Simple 3.43) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "Dancer2::Plugin::LogReport 3pm" .TH Dancer2::Plugin::LogReport 3pm "2023-10-29" "perl v5.36.0" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" Dancer2::Plugin::LogReport \- logging and exceptions via Log::Report .SH "INHERITANCE" .IX Header "INHERITANCE" .Vb 2 \& Dancer2::Plugin::LogReport \& is a Dancer2::Plugin .Ve .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 3 \& # 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\*(Aqre here"; \& \& # Handling user errors cleanly \& if (process( sub {MyApp::Model\->create_user} )) { \& # Success, redirect user elsewhere \& } else { \& # Failed, continue as if submit hadn\*(Aqt 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 \*(Aqmessages\*(Aq; \& session \*(Aqmessages\*(Aq => []; \& } .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" [The Dancer2 plugin was contributed by Andrew Beverley] .PP 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. .PP 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 \s-1STDERR.\s0 .PP Messages within this plugin use the extended Dancer2::Logger::LogReport::Message class rather than the standard Log::Report::Message class. .PP Note that it is currently recommended to use the plugin in all apps within a Dancer2 program, not only some. Therefore, wherever you \f(CW\*(C`use Dancer2\*(C'\fR you should also \f(CW\*(C`use Dancer2::Plugin::LogReport\*(C'\fR. This does not apply if using the same app name (\f(CW\*(C`use Dancer2 appname, \*(AqAlready::Exists\*(Aq\*(C'\fR). In all other modules, you can just \f(CW\*(C`use Log::Report\*(C'\fR. .PP Read the \*(L"\s-1DETAILS\*(R"\s0 in below in this manual-page. .SH "METHODS" .IX Header "METHODS" .ie n .IP "$obj\->\fBfatal_handler\fR()" 4 .el .IP "\f(CW$obj\fR\->\fBfatal_handler\fR()" 4 .IX Item "$obj->fatal_handler()" \&\f(CW\*(C`fatal_handler()\*(C'\fR allows alternative handlers to be defined in place of (or in addition to) the default redirect handler that is called on a fatal error. .Sp Calls should be made with 1 parameter: the subroutine to call in the case of a fatal error. The subroutine is passed 3 parameters: the \s-1DSL,\s0 the message in question, and the reason. The subroutine should return true or false depending on whether it handled the error. If it returns false, the next fatal handler is called, and if there are no others then the default redirect fatal handler is called. .Sp example: Error handler based on \s-1URL\s0 (e.g. \s-1API\s0) .Sp .Vb 11 \& fatal_handler sub { \& my ($dsl, $msg, $reason) = @_; \& return if $dsl\->app\->request\->uri !~ m!^/api/!; \& status $reason eq \*(AqPANIC\*(Aq ? \*(AqInternal Server Error\*(Aq : \*(AqBad Request\*(Aq; \& $dsl\->send_as(JSON => { \& error => 1, \& error_description => $msg\->toString, \& }, { \& content_type => \*(Aqapplication/json; charset=UTF\-8\*(Aq, \& }); \& }; .Ve .Sp example: Return \s-1JSON\s0 responses for requests with content-type of application/json .Sp fatal_handler sub { my ($dsl, \f(CW$msg\fR, \f(CW$reason\fR, \f(CW$default\fR) = \f(CW@_\fR; .Sp .Vb 10 \& (my $ctype = $dsl\->request\->header(\*(Aqcontent\-type\*(Aq)) =~ s/;.*//; \& return if $ctype ne \*(Aqapplication/json\*(Aq; \& status $reason eq \*(AqPANIC\*(Aq ? \*(AqInternal Server Error\*(Aq : \*(AqBad Request\*(Aq; \& $dsl\->send_as(JSON => { \& error => 1, \& description => $msg\->toString, \& }, { \& content_type => \*(Aqapplication/json; charset=UTF\-8\*(Aq, \& }); \& }; .Ve .ie n .IP "$obj\->\fBprocess\fR()" 4 .el .IP "\f(CW$obj\fR\->\fBprocess\fR()" 4 .IX Item "$obj->process()" \&\f(CW\*(C`process()\*(C'\fR is an eval, but one which expects and understands exceptions generated by Log::Report. Any messages will be logged as normal in accordance with the dispatchers, but any fatal exceptions will be caught and handled gracefully. This allows much simpler error handling, rather than needing to test for lots of different scenarios. .Sp In a module, it is enough to simply use the \f(CW\*(C`error\*(C'\fR keyword in the event of a fatal error. .Sp The return value will be 1 for success or 0 if a fatal exception occurred. .Sp See the \*(L"\s-1DETAILS\*(R"\s0 for an example of how this is expected to be used. .Sp This module is configured only once in your application. The other modules which make your website do not need to require this plugin, instead they can \f(CW\*(C`use Log::Report\*(C'\fR to get useful functions like error and fault. .SS "Handlers" .IX Subsection "Handlers" All the standard Log::Report functions are available to use. Please see the \&\*(L"The Reason for the report\*(R" in Log::Report for details of when each one should be used. .PP Log::Report class functionality to class messages (which can then be tested later): .PP .Vb 3 \& notice _\|_x"Class me up", _class => \*(Aqlabel\*(Aq; \& ... \& if ($msg\->inClass(\*(Aqlabel\*(Aq)) ... .Ve .PP Dancer2::Plugin::LogReport has a special message class, \f(CW\*(C`no_session\*(C'\fR, which prevents the message from being saved to the messages session variable. This is useful, for example, if you are writing messages within the session hooks, in which case recursive loops can be experienced. .ie n .IP "$obj\->\fBalert\fR()" 4 .el .IP "\f(CW$obj\fR\->\fBalert\fR()" 4 .IX Item "$obj->alert()" .PD 0 .ie n .IP "$obj\->\fBassert\fR()" 4 .el .IP "\f(CW$obj\fR\->\fBassert\fR()" 4 .IX Item "$obj->assert()" .ie n .IP "$obj\->\fBerror\fR()" 4 .el .IP "\f(CW$obj\fR\->\fBerror\fR()" 4 .IX Item "$obj->error()" .ie n .IP "$obj\->\fBfailure\fR()" 4 .el .IP "\f(CW$obj\fR\->\fBfailure\fR()" 4 .IX Item "$obj->failure()" .ie n .IP "$obj\->\fBfault\fR()" 4 .el .IP "\f(CW$obj\fR\->\fBfault\fR()" 4 .IX Item "$obj->fault()" .ie n .IP "$obj\->\fBinfo\fR()" 4 .el .IP "\f(CW$obj\fR\->\fBinfo\fR()" 4 .IX Item "$obj->info()" .ie n .IP "$obj\->\fBmistake\fR()" 4 .el .IP "\f(CW$obj\fR\->\fBmistake\fR()" 4 .IX Item "$obj->mistake()" .ie n .IP "$obj\->\fBnotice\fR()" 4 .el .IP "\f(CW$obj\fR\->\fBnotice\fR()" 4 .IX Item "$obj->notice()" .ie n .IP "$obj\->\fBpanic\fR()" 4 .el .IP "\f(CW$obj\fR\->\fBpanic\fR()" 4 .IX Item "$obj->panic()" .ie n .IP "$obj\->\fBsuccess\fR()" 4 .el .IP "\f(CW$obj\fR\->\fBsuccess\fR()" 4 .IX Item "$obj->success()" .PD This is a special additional type, equivalent to \f(CW\*(C`notice\*(C'\fR. The difference is that messages using this keyword will have the class \f(CW\*(C`success\*(C'\fR added, which can be used to color the messages differently to the end user. For example, Dancer2::Plugin::LogReport::Message#bootstrap_color uses this to display the message in green. .ie n .IP "$obj\->\fBtrace\fR()" 4 .el .IP "\f(CW$obj\fR\->\fBtrace\fR()" 4 .IX Item "$obj->trace()" .PD 0 .ie n .IP "$obj\->\fBwarning\fR()" 4 .el .IP "\f(CW$obj\fR\->\fBwarning\fR()" 4 .IX Item "$obj->warning()" .PD .SH "DETAILS" .IX Header "DETAILS" This chapter will guide you through the myriad of ways that you can use Log::Report in your Dancer2 application. .PP We will set up our application to do the following: .IP "Messages to the user" 4 .IX Item "Messages to the user" We'll look at an easy way to output messages to the user's web page, whether they be informational messages, warnings or errors. .IP "Debug information" 4 .IX Item "Debug information" We'll look at an easy way to log debug information, at different levels. .IP "Manage unexpected exceptions" 4 .IX Item "Manage unexpected exceptions" We'll handle unexpected exceptions cleanly, in the unfortunate event that they happen in your production application. .IP "Email alerts of significant errors" 4 .IX Item "Email alerts of significant errors" If we do get unexpected errors then we want to be notified them. .IP "Log \s-1DBIC\s0 information and errors" 4 .IX Item "Log DBIC information and errors" We'll specifically look at nice ways to log \s-1SQL\s0 queries and errors when using DBIx::Class. .SS "Larger example" .IX Subsection "Larger example" In its simplest form, this module can be used for more flexible logging .PP .Vb 3 \& get \*(Aq/route\*(Aq => 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\*(Aqs what you wanted"; \& \& # Add debug information, can be caught in syslog by adding \& # the (for instance) syslog dispatcher \& trace "Hello world"; \& }; .Ve .SS "Setup and Configuration" .IX Subsection "Setup and Configuration" To make full use of Log::Report, you'll need to use both Dancer2::Logger::LogReport and Dancer2::Plugin::LogReport. .PP \fIDancer2::Logger::LogReport\fR .IX Subsection "Dancer2::Logger::LogReport" .PP Set up Dancer2::Logger::LogReport by adding it to your Dancer2 application configuration (see Dancer2::Config). By default, all messages will go to \s-1STDERR.\s0 .PP To get all message out \*(L"the Perl way\*(R" (using print, warn and die) just use .PP .Vb 1 \& logger: "LogReport" .Ve .PP 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. .PP To also send messages to your syslog: .PP .Vb 1 \& 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 .Ve .PP To send messages to a file: .PP .Vb 1 \& 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 .Ve .PP See Log::Report::Dispatcher for full details of options. .PP 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. .PP \fIDancer2::Plugin::LogReport\fR .IX Subsection "Dancer2::Plugin::LogReport" .PP To use the plugin, you simply use it in your application: .PP .Vb 4 \& package MyApp; \& use Log::Report (); # use early and minimal once \& use Dancer2; \& use Dancer2::Plugin::LogReport %config; .Ve .PP Dancer2::Plugin::LogReport takes the same \f(CW%config\fR options as Log::Report itself (see \fBLog::Report::import()\fR). .PP If you want to send messages from your modules/models, there is no need to use this specific plugin. Instead, you should simply \&\f(CW\*(C`use Log::Report\*(C'\fR to negate the need of loading all the Dancer2 specific code. .SS "In use" .IX Subsection "In use" \fILogging debug information\fR .IX Subsection "Logging debug information" .PP 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): .PP .Vb 1 \& trace "I\*(Aqm here"; \& \& warning "Something dodgy happened"; \& \& panic "I\*(Aqm bailing out"; \& \& # Additional, special Dancer2 keyword \& success "Settings saved successfully"; .Ve .PP \fIExceptions\fR .IX Subsection "Exceptions" .PP Log::Report is a combination of a logger and an exception system. Messages to be logged are \fIthrown\fR to all listening dispatchers to be handled. .PP This module will also catch any unexpected exceptions: .PP .Vb 8 \& # 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 \*(Aqroute\*(Aq => sub { \& my $foo = 1; \& my $bar = $foo\->{x}; # whoops \& } .Ve .PP For a production application (\f(CW\*(C`show_errors: 1\*(C'\fR), the message saved in the session will be the generic text \*(L"An unexpected error has occurred\*(R". This can be customised in the configuration file, and will be translated. .PP \fISending messages to the user\fR .IX Subsection "Sending messages to the user" .PP To make it easier to send messages to your users, messages at the following levels are also stored in the user's session: \f(CW\*(C`notice\*(C'\fR, \f(CW\*(C`warning\*(C'\fR, \f(CW\*(C`mistake\*(C'\fR, \&\f(CW\*(C`error\*(C'\fR, \f(CW\*(C`fault\*(C'\fR, \f(CW\*(C`alert\*(C'\fR, \f(CW\*(C`failure\*(C'\fR and \f(CW\*(C`panic\*(C'\fR. .PP You can pass these to your template and display them at each page render: .PP .Vb 5 \& hook before_template => sub { \& my $tokens = shift; \& $tokens\->{messages} = session \*(Aqmessages\*(Aq; \& session \*(Aqmessages\*(Aq => []; # Clear the message queue \& } .Ve .PP Then in your template (for example the main layout): .PP .Vb 5 \& [% FOR message IN messages %] \&
\& [% message.toString | html_entity %] \&
\& [% END %] .Ve .PP The \f(CW\*(C`bootstrap_color\*(C'\fR of the message is compatible with Bootstrap contextual colors: \f(CW\*(C`success\*(C'\fR, \f(CW\*(C`info\*(C'\fR, \f(CW\*(C`warning\*(C'\fR or \f(CW\*(C`danger\*(C'\fR. .PP Now, anywhere in your application that you have used Log::Report, you can .PP .Vb 1 \& warning "Hey user, you should now about this"; .Ve .PP and the message will be sent to the next page the user sees. .PP \fIHandling user errors\fR .IX Subsection "Handling user errors" .PP 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. .PP In this example, we do use exceptions, but in a neat, easier to use manner. .PP First, your module/model: .PP .Vb 1 \& package MyApp::CD; \& \& sub update { \& my ($self, %values) = @_; \& $values{title} or error "Please enter a title"; \& $values{description} or warning "No description entered"; \& } .Ve .PP Then, in your controller: .PP .Vb 2 \& package MyApp; \& use Dancer2; \& \& post \*(Aq/cd\*(Aq => sub { \& my %values = ( \& title => param(\*(Aqtitle\*(Aq); \& description => param(\*(Aqdescription\*(Aq); \& ); \& if (process sub { MyApp::CD\->update(%values) } ) { \& success "CD updated successfully"; \& redirect \*(Aq/cd\*(Aq; \& } \& \& template \*(Aqcd\*(Aq => { values => \e%values }; \& } .Ve .PP Now, when \fBupdate()\fR 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 \f(CW\*(C`error\*(C'\fR will have caused the code to stop running, and \fBprocess()\fR will have returned false. \f(CW\*(C`warning\*(C'\fR will have simply logged the warning and not caused the function to stop running. .PP \fILogging \s-1DBIC\s0 database queries and errors\fR .IX Subsection "Logging DBIC database queries and errors" .PP If you use DBIx::Class in your application, you can easily integrate its logging and exceptions. To log \s-1SQL\s0 queries: .PP .Vb 3 \& # Log all queries and execution time \& $schema\->storage\->debugobj(new Log::Report::DBIC::Profiler); \& $schema\->storage\->debug(1); .Ve .PP By default, exceptions from \s-1DBIC\s0 are classified at the level \*(L"error\*(R". This is normally a user level error, and thus may be filtered as normal program operation. If you do not expect to receive any \s-1DBIC\s0 exceptions, then it is better to class them at the level \*(L"panic\*(R": .PP .Vb 4 \& # panic() DBIC errors \& $schema\->exception_action(sub { panic @_ }); \& # Optionally get a stracktrace too \& $schema\->stacktrace(1); .Ve .PP 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: .PP .Vb 3 \& try { $self\->schema\->resultset(\*(AqUnique\*(Aq)\->create() }; \& # Log any messages from try block, but only as trace \& $@\->reportAll(reason => \*(AqTRACE\*(Aq); .Ve .PP \fIEmail alerts of exceptions\fR .IX Subsection "Email alerts of exceptions" .PP 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: .PP .Vb 2 \& # 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\er\enmsg=\*(Aq%msg%\*(Aq\er\enseverity=\*(Aq%syslogseverity\-text%\*(Aq" \& $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 == \*(Aqlocal0\*(Aq and $syslogseverity < 3 then :ommail:;mailBody \& $ActionExecOnlyOnceEveryInterval 0 .Ve .PP With the above configuration, you will only be emailed of severe errors, but can view the full log information in /var/log/myapp.log .SH "CONFIGURATION" .IX Header "CONFIGURATION" All configuration is optional. The example configuration file below shows the configuration options and defaults. .PP .Vb 10 \& plugins: \& LogReport: \& # Whether to handle Dancer HTTP errors such as 404s. Currently has \& # no effect due to unresolved issues saving messages to the session \& # and accessing the DSL at that time. \& handle_http_errors: 1 \& # Where to forward users in the event of an uncaught fatal \& # error within a GET request \& forward_url: / \& # Or you can specify a template instead [1.13] \& forward_template: error_template_file # Defaults to empty \& # For a production server (show_errors: 0), this is the text that \& # will be displayed instead of unexpected exception errors \& fatal_error_message: An unexpected error has occurred \& # The levels of messages that will be saved to the session, and \& # thus displayed to the end user \& session_messages: [ NOTICE, WARNING, MISTAKE, ERROR, FAULT, ALERT, FAILURE, PANIC ] .Ve .SH "SEE ALSO" .IX Header "SEE ALSO" This module is part of Log-Report distribution version 1.36, built on October 27, 2023. Website: \fIhttp://perl.overmeer.net/CPAN/\fR .SH "LICENSE" .IX Header "LICENSE" Copyrights 2007\-2023 by [Mark Overmeer ]. For other contributors see ChangeLog. .PP This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See \fIhttp://dev.perl.org/licenses/\fR