先程のエントリの続きです。
http://amon.64p.org/logging.html
amon2のdocumentには、Log::Minimal 推奨とありますが、私の場合
- 長年、Log::Log4perl を使用してきました
- Log::Minimal って、ファイルへのログ出力方法や書式設定がよく...
ということなので、Log::Log4perl で試してみました。
設定ファイル - TestAmon2App/config/development.pl
次のようにlogの設定を追加.
※Amon2では使用する設定ファイル名を $ENV{PLACK_ENV} から参照することで、開発,テスト,本番の設定ファイルを切り替えることができるそうです
use File::Spec; use File::Basename qw(dirname); my $basedir = File::Spec->rel2abs(File::Spec->catdir(dirname(__FILE__), '..')); my $dbpath = File::Spec->catfile($basedir, 'db', 'development.db'); +{ 'DBI' => [ "dbi:SQLite:dbname=$dbpath", '', '', +{ sqlite_unicode => 1, } ], log=>{ 'log4perl.rootLogger'=> 'DEBUG, LOGFILE', # 'log4perl.rootLogger'=> 'INFO, LOGFILE', 'log4perl.appender.LOGFILE'=>'Log::Log4perl::Appender::File', 'log4perl.appender.LOGFILE.filename'=>'/home/endo/tmp/web_app.log', 'log4perl.appender.LOGFILE.mode'=>'append', 'log4perl.appender.LOGFILE.layout'=>'PatternLayout', 'log4perl.appender.LOGFILE.layout.ConversionPattern'=>'%d [%p] %m %n' } };
ルートクラス
動作は遅いでしょうが、今回はルートクラスからLog::Log4perlのmethodを呼びます
package TestAmon2App; use strict; use warnings; use utf8; our $VERSION='0.01'; use 5.008001; use Log::Log4perl; use TestAmon2App::DB::Schema; use TestAmon2App::DB; use Data::Dumper; use parent qw/Amon2/; # Enable project local mode. __PACKAGE__->make_local_context(); my $schema = TestAmon2App::DB::Schema->instance; my $CONF = TestAmon2App->load_config(); Log::Log4perl::init($CONF->{log}); ########ココ my $LOGGER = Log::Log4perl::get_logger("rootLogger"); ########ココ sub db { my $c = shift; if (!exists $c->{db}) { my $conf = $c->config->{DBI} or die "Missing configuration about DBI"; $c->{db} = TestAmon2App::DB->new( schema => $schema, connect_info => [@$conf], # I suggest to enable following lines if you are using mysql. # on_connect_do => [ # 'SET SESSION sql_mode=STRICT_TRANS_TABLES;', # ], ); } $c->{db}; } ########↓ココ sub debug { my ($self,@msg) = @_; $LOGGER->debug(@msg); } sub error { my ($self,@msg) = @_; $LOGGER->error(@msg); } sub warn { my ($self,@msg) = @_; $LOGGER->warn(@msg); } sub info { my ($self,@msg) = @_; $LOGGER->info(@msg); } 1; __END__
コントローラ?
では、実際にログを出力してみます。
package TestAmon2App::Web::Dispatcher; use strict; use warnings; use utf8; use Amon2::Web::Dispatcher::RouterBoom; any '/' => sub { my ($c) = @_; $c->info('This is info log for test.'); ######## ココ my $counter = $c->session->get('counter') || 0; $counter++; $c->session->set('counter' => $counter); return $c->render('index.tx', { counter => $counter, }); }; post '/reset_counter' => sub { my $c = shift; $c->session->remove('counter'); return $c->redirect('/'); }; post '/account/logout' => sub { my ($c) = @_; $c->session->expire(); return $c->redirect('/'); }; 1;
と書いておいて
$ tail -f /home/endo/tmp/web_app.log 2014/11/16 06:13:35 [INFO] This is info log for test.
このエントリは以上!!