Debian Codegraph @

lemonldap-ng-common/lib/Lemonldap/NG/Common/Logger/Loki.pm

raw
1 package Lemonldap::NG::Common::Logger::Loki;
2
3 use strict;
4 use JSON;
5 use Lemonldap::NG::Common::UserAgent;
6 use Sys::Hostname;
7 use Time::HiRes qw(time);
8
9 our $VERSION = '2.22.0';
10
11 sub new {
12 my ( $class, $conf, %args ) = @_;
13 my $self = bless {}, $class;
14 my $level = $conf->{logLevel} || 'info';
15 $self->{deferDir} = $conf->{lokiDeferDir};
16 $self->{url} = $conf->{lokiUrl} || 'http://localhost:3100/loki/api/v1/push';
17 $self->{label} = $conf->{lokiLabel} || 'llng';
18 $self->{j} = JSON->new->canonical;
19 $self->{ua} = Lemonldap::NG::Common::UserAgent->new($conf)
20 unless $self->{deferDir};
21 $self->{instance} = $conf->{lokiInstance} || hostname;
22 $self->{env} = $conf->{lokiEnv} || 'prod';
23 $self->{tenant} = $conf->{lokiTenant};
24 $self->{authorization} = $conf->{lokiAuthorization};
25 $self->{tenantHeader} = $conf->{lokiTenantHeader} || 'X-Scope-OrgID';
26 $self->{proxy} = $conf->{lokiProxy};
27 $self->{service} =
28 $args{user}
29 ? ( $conf->{lokiUserService} || 'auth' )
30 : ( $conf->{lokiService} || 'llng' );
31 my $show = 1;
32
33 unless ( $self->{deferDir} ) {
34 foreach (qw(url proxy)) {
35 if ( $self->{$_} ) {
36 my $h = eval { URI->new( $self->{$_} )->host };
37 die 'Bad loki' . ucfirst($_) . ' value' if $@ or !$h;
38 $self->{host} = $h if $_ eq 'url';
39 }
40 }
41 }
42
43 foreach (qw(error warn notice info debug)) {
44 if ($show) {
45 my $name = $_;
46 eval "sub $_ {shift->log('$name', \@_)}";
47 die $@ if ($@);
48 }
49 else {
50 eval qq'sub $_ {1}';
51 }
52 $show = 0 if ( $level eq $_ );
53 }
54 die "Unknown logLevel $level" if $show;
55 return $self;
56 }
57
58 sub log {
59 my ( $self, $level, $message ) = @_;
60 my $logEntry = {
61 streams => [ {
62 stream => {
63 job => $self->{label},
64 instance => $self->{instance},
65 level => $level,
66 env => $self->{env},
67 service => $self->{service},
68 },
69 values =>
70 [ [ sprintf( "%19d", time * 1000000000 ), $message ] ],
71 },
72 ],
73 };
74 my $req = HTTP::Request->new(
75 POST => ( $self->{proxy} || $self->{url} ),
76 [
77 ( $self->{proxy} ? ( Host => $self->{host} ) : () ),
78 'Content-Type' => 'application/json',
79 (
80 $self->{authorization}
81 ? ( 'Authorization' => $self->{authorization} )
82 : ()
83 ),
84 (
85 $self->{tenant} ? ( $self->{tenantHeader} => $self->{tenant} )
86 : ()
87 )
88 ],
89 $self->{j}->encode($logEntry)
90 );
91 if ( $self->{deferDir} ) {
92 $req = $req->as_string;
93 if ( open my $f, '>', "$self->{deferDir}/" . time . ".$$" ) {
94 print $f $req;
95 close $f;
96 }
97 else {
98 print STDERR
99 "# UNABLE TO STORE LOKI LOG: $!, here is the content:\n$req";
100 }
101 }
102 else {
103 my $response = $self->{ua}->request($req);
104 unless ( $response->is_success ) {
105 print STDERR
106 "Unable to push log to loki\nMessage: $message\nResponse: "
107 . $response->status_line . "\n";
108 }
109 }
110 }
111
112 1;