Log4perlでスレッドIDを出力する

この記事は2年以上前に書いたものです。
そのため情報が古い可能性があります。ご了承ください。m(_ _)m

Log4perlでスレッドIDを出力する方法が分からなかったのでググったところ、
以下の頁が参考になった。

Log4perl log rotation in threadpool environment
Log::Log4perl::MDC – search.cpan.org

#!/usr/bin/perl

use strict;
use warnings;

use threads;
use Log::Log4perl qw(:easy);
Log::Log4perl->easy_init({level => $INFO, layout => "%d %02X{TID} %p %F{1} %L> %m %n"});

# 標準エラーのバッファリングを止める
use IO::Handle;
STDERR->autoflush;

# メインスレッドを0
Log::Log4perl::MDC->put("TID", '0');


my ($thr1, $thr2, $thr3) = (0) x 3;
$thr1 = threads->create(\&func);
INFO 'threads create: tid='.$thr1->tid();

$thr2 = threads->create(\&func);
INFO 'threads create: tid='.$thr2->tid();

$thr3 = threads->create(\&func);
INFO 'threads create: tid='.$thr3->tid();

$thr1->join();
$thr2->join();
$thr3->join();

sub func{
    Log::Log4perl::MDC->put("TID", threads->tid());

    INFO 'start';

    my $w = int(rand 10);
    INFO 'wait: ' . $w;
    sleep $w;

    INFO 'end';
    Log::Log4perl::MDC->remove();
}

↑のスクリプトを実行した場合、↓のような出力が得られる。

% perl log_threads.pl
2013/05/05 00:20:02 01 INFO log_threads.pl 34> start
2013/05/05 00:20:02 00 INFO log_threads.pl 19> threads create: tid=1
2013/05/05 00:20:02 01 INFO log_threads.pl 37> wait: 6
2013/05/05 00:20:03 00 INFO log_threads.pl 22> threads create: tid=2
2013/05/05 00:20:03 02 INFO log_threads.pl 34> start
2013/05/05 00:20:03 02 INFO log_threads.pl 37> wait: 2
2013/05/05 00:20:03 00 INFO log_threads.pl 25> threads create: tid=3
2013/05/05 00:20:03 03 INFO log_threads.pl 34> start
2013/05/05 00:20:03 03 INFO log_threads.pl 37> wait: 3
2013/05/05 00:20:05 02 INFO log_threads.pl 40> end
2013/05/05 00:20:06 03 INFO log_threads.pl 40> end
2013/05/05 00:20:08 01 INFO log_threads.pl 40> end
カテゴリー: プログラム タグ: パーマリンク

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です