read from /home/nodelogs/
[eg5120] / parse-node-logs.pl
1 #!/usr/bin/perl
2 use strict;
3 use warnings;
4
5 use POSIX qw(strftime);
6 use File::Slurp;
7 use DBD::Pg;
8 use Data::Dump qw(dump);
9 use autodie;
10
11 my $path = '/home/nodelogs/c405f97667784094bca5cfa52af0bcf1/';
12
13 # select _id,json->'received',time,to_timestamp((json->>'received')::int8/1000) - interval '1 hour' from nodelog ;
14
15 my $dbh = DBI->connect("dbi:Pg:dbname=eg5120", "dpavlin", "", { RaiseError => 1 });
16 $dbh->do( qq{ truncate table nodelog } ); # FIXME
17 my $sth = $dbh->prepare(qq{insert into nodelog (time,json) values (?,?)});
18
19 foreach my $filename (
20                 sort(glob("$path/node-red-out__2023-07-*")),
21                 "$path/node-red-out.log"
22         ) {
23         warn "# $filename";
24         open(my $log, '<', $filename);
25         my $in_json = 0;
26         my $json;
27         my $year = $1 if $filename =~ m/__(20\d\d)-/;
28         $year ||= (localtime)[5] + 1900;
29         my $time;
30         while(<$log>) {
31                 chomp;
32                 #warn "## $in_json -->$_<--\n";
33                 if ( m/(\d+ \w+)\s+(\d\d:\d\d:\d\d) - \Q[info] [debug:debug 1]\E/ ) {
34                         $time = $1 . ' ' . $year . ' ' . $2;
35                         #warn "# time $time\n";
36                 } elsif ( $_ eq '{' ) {
37                         $json .= $_;
38                         $in_json = 1;
39                         #warn "+ in_json";
40                 } elsif ( $in_json ) {
41
42                         s/\s(\S+):\s/"$1":/g;   # fix names quoting
43                         s/'/"/g;                # replace ' with "
44                         $json .= $_;
45
46                         if ( $_ eq '}' ) {
47                                 $in_json = 0;
48                                 #warn "- in_json";
49                                 warn ">>> $time [[[[ $json ]]]]";
50                                 write_file '/dev/shm/json', $json;
51                                 $sth->execute( $time, $json );
52                                 $json = '';
53                         }
54                 }
55
56         }
57 }
58