Skip to content

Commit

Permalink
print log messages without timestamps to STDERR when deployed with sy…
Browse files Browse the repository at this point in the history
…stemd
  • Loading branch information
kraih committed Jun 30, 2017
1 parent 6c0d311 commit 6841633
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 3 deletions.
5 changes: 4 additions & 1 deletion Changes
@@ -1,5 +1,8 @@

7.34 2017-06-29
7.34 2017-06-30
- Improved Mojo::Log to print log messages without timestamps to STDERR when
deployed with systemd.
- Improved Mojo::DOM performance slightly.

7.33 2017-06-05
- Added EXPERIMENTAL support for :matches pseudo-class and :not pseudo-class
Expand Down
16 changes: 14 additions & 2 deletions lib/Mojo/Log.pm
Expand Up @@ -6,7 +6,7 @@ use Fcntl ':flock';
use Mojo::File;
use Mojo::Util 'encode';

has format => sub { \&_format };
has format => sub { shift->short ? \&_short : \&_default };
has handle => sub {

# STDERR
Expand All @@ -19,6 +19,7 @@ has history => sub { [] };
has level => 'debug';
has max_history_size => 10;
has 'path';
has short => sub { !!$ENV{JOURNAL_STREAM} && !shift->path };

# Supported log levels
my %LEVEL = (debug => 1, info => 2, warn => 3, error => 4, fatal => 5);
Expand Down Expand Up @@ -47,7 +48,7 @@ sub new {

sub warn { shift->_log(warn => @_) }

sub _format {
sub _default {
'[' . localtime(shift) . '] [' . shift() . '] ' . join "\n", @_, '';
}

Expand All @@ -66,6 +67,8 @@ sub _message {
$self->append($self->format->(@$msg));
}

sub _short { shift; '[' . shift() . '] ' . join "\n", @_, '' }

1;

=encoding utf8
Expand Down Expand Up @@ -168,6 +171,15 @@ Maximum number of logged messages to store in L</"history">, defaults to C<10>.
Log file path used by L</"handle">.
=head2 short
my $bool = $log->short;
$log = $log->short($bool);
Generate short log messages without a timestamp, suitable for systemd, defaults
to auto-detection based on the presence of a L</"path"> and the
C<JOURNAL_STREAM> environment variable.
=head1 METHODS
L<Mojo::Log> inherits all methods from L<Mojo::EventEmitter> and implements the
Expand Down
17 changes: 17 additions & 0 deletions t/mojo/log.t
Expand Up @@ -50,6 +50,23 @@ $log->format(
like $log->format->(time, 'debug', qw(Test 1 2 3)), qr/^debug:\d+:Test:1:2:3$/,
'right format';

# systemd
{
$log = Mojo::Log->new;
ok !$log->short, 'systemd has not been detected';
like $log->format->(time, 'debug', 'Test 123'),
qr/^\[.*\] \[debug\] Test 123\n$/, 'right format';
local $ENV{JOURNAL_STREAM} = '1:23456';
$log = Mojo::Log->new;
ok $log->short, 'systemd has been detected';
like $log->format->(time, 'debug', 'Test 123'), qr/^\[debug\] Test 123\n$/,
'right format';
$log = Mojo::Log->new(path => $path);
ok !$log->short, 'a path will be used';
like $log->format->(time, 'debug', 'Test 123'),
qr/^\[.*\] \[debug\] Test 123\n$/, 'right format';
}

# Events
$log = Mojo::Log->new;
my $msgs = [];
Expand Down

0 comments on commit 6841633

Please sign in to comment.