Skip to content

Latest commit

 

History

History
96 lines (76 loc) · 3.54 KB

Logging.md

File metadata and controls

96 lines (76 loc) · 3.54 KB

Writing to Logs

You are serious about security auditing, so you want to log access to your app.

I've added Mojo::Log to the Controller. I could have used Mojolicious::Plugin::AccessLog which is simpler - not sure why I decided on Mojo::Log.

lib/SessionTutorial/Controller/Tutorial.pm

At the top of the controller, I add

use Mojo::Log;

my $log = Mojo::Log->new(path => 'log/access.log', level => 'info');

and in the on_user_login method, I write to the log with

  if (check_credentials($self, $username, $password)) {
	
    $log->info(join "\t", "Login succeeded: $username", $self->tx->remote_address);

  }
  else {
    $log->info(join "\t", "Login FAILED: $username", $self->tx->remote_address);
  }

Because you can run as many logs for many different purposes, I create a log directory to keep them in with mkdir log . I use the join in the call to log because the method puts each list item on a separate line.

Notice that you now also get log/development.log for free. This log stores all the messages from morbo such as routing and rendering. If you're running hypnotoad in a production environment, the log name will be log/production.log, naturally.

TODO - add link to hypnotoad and explain

Try it out

Authenticate at the Login page and check log/access.log for something like

[Thu Nov 16 18:59:16 2017] [info] Login FAILED: francisco	127.0.0.1
[Thu Nov 16 19:01:34 2017] [info] Login succeeded: julian	127.0.0.1

TODO - Except that during testing I used the controller's log instead of the one I instantiated with the path, so also take a look at log/development.log

Test the app

In the test, you can change the log level using $t->app->log->level('fatal');

prove -v -l t/04_logging.t

Discussion on testing Mojo::Log

You should check the last 10 messages in the log with $t->app->log->history but subscribing to the log using on as in $self->app->log->on(message => sub { my ($log, $level, @lines) = @_; say "$level: ", @lines; }); is another possibility

Don't instantiate the log yourself.

PROVE PROVE PROVE PROVE PROVE use prove -v -l t/04_logging.t and the history gets filled

Next Step

A navigational menu helps the user get where they want quickly. Let's move the Logout link to a template to make it available from all protected pages. Instructions continue in Templates.

More information

There are a number of blogs and pages that will get you going with logging. Perhaps the quickest is Mojolicious::Plugin::AccessLog, a plugin to easily generate an access log. You only need to consider where the log will be and whether you want to customize the log format. It's a one line command in both Mojolicious and Mojolicious::Lite.

And in various examples in the Mojolicious::Guides::Cookbook