LoginSignup
1
1

More than 5 years have passed since last update.

改行を含むMySQLログを整形するperlスクリプト

Posted at

中身

qb
#!/usr/bin/perl
use strict;

my ($time, $id, $command, $argument, @lines) = ();

while(my $line = <>){
  chomp $line;

  if(
    $line =~ /^(\d{6}\s+\d+:\d+:\d+)\s+(\d+)\s([A-Z]\w+)(.*)$/ ||
    $line =~ /^(\t\t)\s*(\d+)\s([A-Z]\w+)(.*)$/
  ){
    _flush();
    ($time, $id, $command, $argument) = ($1, $2, $3, $4);
  } else {
    $line =~ s/^\s+/ /; # 行頭の空白は1つ
    $line =~ s/\s+$//;  # 行末の空白は取り除く
    $line =~ s/^(\S)/ $1/;
    push @lines, $line;
  }
}

sub _flush {
  print sprintf("%15s %9s %-11s %s %s\n",
          $time,
          $id,
          $command,
          $argument,
          join('', @lines),);
  ($time, $id, $command, $argument, @lines) = ();
}
qbt
#!/usr/bin/perl
use strict;

my ($time, $id, $command, $argument, @lines) = ();
my $tmp = '';

while(my $line = <>){
  chomp $line;

  if(
    $line =~ /^(\d{6}\s+\d+:\d+:\d+)\s+(\d+)\s([A-Z]\w+)(.*)$/ ||
    $line =~ /^(\t\t)\s*(\d+)\s([A-Z]\w+)(.*)$/
  ){
    _flush();
    ($tmp, $id, $command, $argument) = ($1, $2, $3, $4);
    if($tmp =~ /^(\d{6}) ([ \d]\d):(\d\d):(\d\d)/){
      $time = sprintf("%06d %02d:%02d:%02d", $1, $2, $3, $4);
    }
  } else {
    $line =~ s/^\s+/ /;
    $line =~ s/\s+$//;
    $line =~ s/^(\S)/ $1/;
    push @lines, $line;
  }
}

sub _flush {
  print sprintf("%15s %9s %-11s %s %s\n",
          $time,
          $id,
          $command,
          $argument,
          join('', @lines),);
  ($id, $command, $argument, @lines) = ();
}

使い方

unixコマンドライクなフィルタのように使ってください。
qbtは拾える限り時刻を拾います。
ネーミングはQuery-log Beautifier (with Timestamp) のつもり。
必要だったら実行属性付けてください。

$ tail -f mysql.log | qbt

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1