| 1 | package MYDan::Util::Say; | ||
| 2 | |||
| 3 | =head1 NAME | ||
| 4 | |||
| 5 | MYDan::Util::Say - thread safe logger | ||
| 6 | |||
| 7 | =head1 SYNOPSIS | ||
| 8 | |||
| 9 | use MYDan::Util::Say; | ||
| 10 | |||
| 11 | my $log = MYDan::Util::Say->new( $handle ); | ||
| 12 | |||
| 13 | $log->say( 'foo', 'bar' ); | ||
| 14 | |||
| 15 | =cut | ||
| 16 | use strict; | ||
| 17 | use warnings; | ||
| 18 | |||
| 19 | use Carp; | ||
| 20 | use POSIX; | ||
| 21 | use Thread::Semaphore; | ||
| 22 | |||
| 23 | =head1 HANDLE | ||
| 24 | |||
| 25 | Must be a writable handle. Defaults to STDERR. | ||
| 26 | |||
| 27 | =cut | ||
| 28 | our $HANDLE = \*STDERR; | ||
| 29 | |||
| 30 | sub new | ||
| 31 | { | ||
| 32 | my ( $class, $handle ) = splice @_; | ||
| 33 | bless { handle => $handle || $HANDLE, mutex => Thread::Semaphore->new() }, | ||
| 34 | ref $class || $class; | ||
| 35 | } | ||
| 36 | |||
| 37 | =head1 METHODS | ||
| 38 | |||
| 39 | =head3 say( @list ) | ||
| 40 | |||
| 41 | I<say> @list to log. Returns invoking object. | ||
| 42 | |||
| 43 | =cut | ||
| 44 | sub say | ||
| 45 | { | ||
| 46 | my $self = shift; | ||
| 47 | my $handle = $self->{handle}; | ||
| 48 | if ( @_ ) | ||
| 49 | { | ||
| 50 | $self->{mutex}->down(); | ||
| 51 | syswrite $handle, POSIX::sprintf( @_ ) . "\n"; | ||
| 52 | $self->{mutex}->up(); | ||
| 53 | } | ||
| 54 | return $self; | ||
| 55 | } | ||
| 56 | |||
| 57 | 1; |