package Log::Simple;
use strict;
use warnings;

our $VERSION = '0.01';
use base 'Exporter';
our @EXPORT = qw(log_config debug info warn error fatal );
use POSIX qw(strftime);
use Fcntl ':flock';

my $fh;
my $level;
use Data::Dump qw(dump);

my $log_level = {
	DEBUG => 1,
	INFO => 2,
	WARN => 3,
	ERROR => 4,
	FATAL => 5,
};

sub log_config
{
	my (%opts) = @_;
	if ( my $path = $opts{path})
	{
		open $fh, '>>', $path
			or die "Can't open log file $path : $!";
	}
	else
	{
		$fh = \*STDERR;
	}
	$level = $log_level->{ $opts{level} // 'DEBUG' } ;
}

sub info(@)
{
	_log('INFO', @_);
}

sub debug(@)
{
	_log('DEBUG', @_);
}

sub error(@)
{
	_log('ERROR', @_);
}

sub warn(@)
{
	_log('WARN', @_);
}

sub fatal(@)
{
	_log('FATAL', @_);
	die;
}


sub _log
{
	my ($level_str, @args) = @_;
	my $_level = $log_level->{$level_str};
	return if $_level < $level;

	my $now_string = strftime "%D %T", localtime;
	my ($pkg, $file, $line) = caller(1);
	my $localtion = "$file ($line)";

	@args = map {
		if ( ref $_)
		{
			dump($_);
		}
		else
		{
			$_;
		}
	} @args;

	flock $fh, LOCK_EX;
	print $fh "$now_string [ $level_str ] ", @args, ' @ ' , $localtion, "\n"
		or die $!;
	flock $fh, LOCK_UN;
}



1;

__END__

=encoding utf-8

=head1 NAME

Log::Simple - Simple Logger

=head1 SYNOPSIS

    use Log::Simple;
	
	log_config(path => '/tmp/logfile', level => 'INFO');
	debug "a debug message";
	info "a info message";
	warn "a warn message";
	error "a error message";
	fatal "a fatal message" # die

=head1 DESCRIPTION

=head1 METHODS
	
	log_config

	debug

	info

	warn

	error

	fatal

=head1 AUTHOR

electricface, E<lt>electricface@qq.comE<gt>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2015 by electricface.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut
