Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

中身

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

hgzap
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away