lib/MGH_Biostat/TravEpi/SimpleRulesBase/Logger.pm


package MGH_Biostat::TravEpi::SimpleRulesBase::Logger;
use Modern::Perl '2012';
use experimental 'switch';
use POSIX 'strftime';
use Plack::Request;
use JSON::Tiny 'encode_json';

sub new {
    my $class = shift;
    my ($print_obj) = @_;

    my $self = bless {}, $class;
    $self->{'print_obj'} = $print_obj;
    return $self;
}

our $filters = {
    'drop_uas' => [
        qr/UptimeRobot/i,
    ],
    'remove_ips' => [
        '127.0.0.1',         # localhost
        '155.52.221.6',      # proxy
        '170.223.178.73',    # proxy
    ],
};

sub log {
    my $self = shift;
    my ( $env, $hash, $lang, $action, $extra ) = @_;

    # don't log if the magic cookie is set (used when demoing sites at conventions, etc.)
    my $req     = Plack::Request->new($env);
    my $cookies = $req->cookies;
    return if ( defined( $cookies->{'nologging'} ) and ( $cookies->{'nologging'} eq 'stop-logging' ) );

    my $ua = $env->{'HTTP_USER_AGENT'} // '';

    # don't log if one of the "drop uas"
    return if ( $ua ~~ $filters->{'drop_uas'} );

    my $time = strftime( '%Y-%m-%d %H:%M:%S', localtime() );

    # extract the various IP addresses, removing those in our filters list
    my $ips = [
        grep { !( $_ ~~ $filters->{'remove_ips'} ); }
          grep { $_; }
          ( split( /\s*,\s*/, ( $env->{'HTTP_X_FORWARDED_FOR'} // '' ) ), $env->{'REMOTE_ADDR'} )
    ];

    $extra //= '';

    # @TODO add a protection against tabs here; *and write a test*
    my $line = join( "\t" => ( $time, $hash, encode_json($ips), $lang, $action, $ua, $extra ) ) . "\n";
    $self->{'print_obj'}->print($line);
}

1;