Perl error log

Chapter 13. Logging Logging is recording messages from my program so I can watch its progress or look at what happened later. This is much larger than recording warnings or … - Selection from Mastering Perl [Book]

Chapter 13. Logging

Logging is recording messages from my program so I can watch its progress
or look at what happened later. This is much larger than recording warnings
or errors from my program since I can also log messages when things are
going well, instead of just when things don’t work. Along with
configuration, logging is one of the features missing from most Perl
applications, but it’s incredibly easy to add.

Recording Errors and Other Information

Web applications already have it made. They can send things to STDERR (through
whichever mechanism or interface the program might use), and they show up
in the web server error log.[48]Other programs have to work harder. In general, logging is
not as simple as opening a file, appending some information, and closing
the file. That might work if the program won’t run more than once at the
same time and definitely finishes before it will run again. For any other
case, it’s possible that two runs of the program running at the same time
will try to write to the same file. Output buffering and the race for
control of the output file mean that somebody is going to win, and not all
of the output may make it into the file.

Logging, however, doesn’t necessarily mean just adding something to
a file. Maybe I want to shove the messages into a database, show them on
the screen, send them to a system logger (such as syslogd), or more than one of
those. I might want to send them directly to my email or pager. Indeed, if
something is going wrong on one machine, to ensure that I see the message
I might want to send it to another machine. I might want to send a message
to several places at the same time. Not only should it show up in the
logfile, but it should show up on my screen. I might want different parts
of my program to log things differently. Application errors might go to
customer service people while database problems go to the database
administrators.

If that’s not complicated enough, I might want different levels of
logging. By assigning messages an importance, I can decide which messages
I want to log. For instance, I might have a debugging level that outputs
quite a bit of information because I want to see as much as possible when
I need to fix a problem. When I put my program into production, I don’t
want to fill up my log with that extra debugging information, but I still
want to see other important messages.

Putting all of that together, I need:

  • Output to multiple places

  • Different logging for different program parts

  • Different levels of logging

There are several modules that can handle all of those, including
Michael Schilli’s Log::Log4perl
and Dave Rolsky’s Log::Dispatch, but I’m
only going to talk about one of them. Once I have the basic concept, I do
the same thing with only minor interface details. Indeed, parts of
Log::Log4perl use
Log::Dispatch.

Log4perl

The Apache/Jakarta project created a Java logging mechanism called log4j, which has all of the features I
mentioned in the last section. Language wars aside, it’s a nice package.
It’s so nice, in fact, that Mike Schilli and Kevin Goess ported it to Perl.

My logging can be really simple. This short example loads
Log::Log4perl with the :easy import tag, which gives me $ERROR: a constant to denote the logging level,
and ERROR as the function to log
messages for that level. I use easy_init to set up the default logging by
telling it what sort of messages that I want to log, in this case those of
type $ERROR. After that, I can use
ERROR. Since I haven’t said anything
about where the logging output should go, Log::Log4perl
sends it to my terminal:

#!/usr/bin/perl
# log4perl-easy1.pl

use Log::Log4perl qw(:easy);

Log::Log4perl->easy_init( $ERROR );

ERROR( "I've got something to say!" );

The error message I see on the screen has a date- and timestamp, as
well as the message I sent:

2006/10/22 19:26:20 I've got something to say!

If I don’t want to go to the screen, I can give easy_init some extra information to let it know
what I want it to do. I use an anonymous hash to specify the level of
logging and the file I want it to go to. Since I want to append to my log,
I use a >> before the filename
just as I would with Perl’s open. This
example does the same thing as the previous one, save that its output goes
to error_log. In
Log::Log4perl parlance, I’ve configured an
appender:

#!/usr/bin/perl
# log4perl-easy2.pl

use Log::Log4perl qw(:easy);

Log::Log4perl->easy_init(
        {
        level => $ERROR,
        file  => ">> error_log",
        }
        );

ERROR( "I've got something to say!" );

I can change my program a bit. Perhaps I want to have some debugging
messages. I can use the DEBUG function
for those. When I set the target for the message, I use the special
filename STDERR, which stands in for
standard error:

#!/usr/bin/perl
# log4perl-easy3.pl

use strict;
use warnings;

use Log::Log4perl qw(:easy);

Log::Log4perl->easy_init(
        {
        file  => ">> error_log",
        level => $ERROR,
        },

        {
        file  => "STDERR",
        level => $DEBUG,
        }
        );

ERROR( "I've got something to say!" );

DEBUG( "Hey! What's going on in there?" );

My error messages go to the file, and my debugging messages go to
the standard error. However, I get both on the screen!

2006/10/22 20:02:45 I've got something to say!
2006/10/22 20:02:45 Hey! What's going on in there?

I don’t have to be content with simply logging messages, though.
Instead of a string argument, I give the logging routines an anonymous
subroutine to execute. This subroutine will run only when I’m logging at
that level. I can do anything I like in the subroutine, and the return
value becomes the log message:

#!/usr/bin/perl
# log4perl-runsub.pl

use strict;
use warnings;

use Log::Log4perl qw(:easy);

Log::Log4perl->easy_init(
        {
        file  => "STDERR",
        level => $DEBUG,
        }
        );
        
DEBUG( sub { 
        print "Here I was!";      # To STDOUT
        return "I was debugging!" # the log message
        } );

The messages are hierarchical; therefore configuring a message
level, such as $DEBUG, means that
messages for that level and all lower levels reach that appender.
Log::Log4perl defines five levels, where debugging is
the highest level (i.e., I get the most output from it). The DEBUG level gets the messages for all levels,
whereas the ERROR level gets the
messages for itself and FATAL. Here are
the levels and their hierarchy:

  • DEBUG

  • INFO

  • WARN

  • ERROR

  • FATAL

Keep in mind, though, that I’m really configuring the appenders, all
of which get a chance to log the output. Each appender looks at the
message and figures out if it should log it. In the previous example, both
the error_log and STDERR appenders knew that they logged messages
at the ERROR level, so the ERROR messages showed up in both places. Only
the STDERR appender thinks it should
log messages at the DEBUG level, so the
DEBUG messages only show up on
screen.

Configuring Log4perl

The easy technique I used earlier defined a default logger that it secretly used.
For more control, I can create my own directly. In most applications,
this is what I’m going to do. This happens in two parts. First, I’ll
load Log::Log4perl and configure it. Second, I’ll get
a logger instance.

To load my own configuration, I replace my earlier call to
easy_init with init, which takes a filename argument. Once
I’ve initialized my logger, I still need to get an instance of the
logger (since I can have several instances going at the same time) by
calling get_logger. The easy_init method did this for me behind the
scenes, but now that I want more flexibility I have a bit more work to
do. I put my instance in $logger and
have to call the message methods such as error on that instance:

#!/usr/bin/perl
# root-logger.pl

use Log::Log4perl;

Log::Log4perl::init( 'root-logger.conf' );

my $logger = Log::Log4perl->get_logger;

$logger->error( "I've got something to say!" );

Now I have to configure Log::Log4perl. Instead
of easy_init making all of the
decisions for me, I do it myself. For now, I’m going to stick with a
single root logger. Log::Log4perl can have different
loggers in the same program, but I’m going to ignore those. Here’s a
simple configuration file that mimics what I was doing before, appending
messages at or below the ERROR level
to a file error_log:

# root-logger.conf
log4perl.rootLogger               = ERROR, myFILE

log4perl.appender.myFILE          = Log::Log4perl::Appender::File
log4perl.appender.myFILE.filename = error_log
log4perl.appender.myFILE.mode     = append
log4perl.appender.myFILE.layout   = Log::Log4perl::Layout::PatternLayout
log4perl.appender.myFILE.layout.ConversionPattern = [%c] (%F line %L) %m%n

The first line configures rootLogger. The first argument is the logging
level, and the second argument is the appender to use. I make up a name
that I want to use, and myFILE seems good
enough.

After I configure the logger, I configure the appender. Before I
start, there is no appender even though I’ve named one
(myFILE), and although I’ve given it a name,
nothing really happens. I have to tell Log4perl what myFile
should do.

First, I configure myFile to use
Log::Log4perl::Appender::File. I could use any of the
appenders that come with the module (and there are many), but I’ll keep
it simple. Since I want to send it to a file, I have to tell
Log::Log4perl::Appender::File which file to use and
which mode it should use. As with my easy example, I want to append to
error_log. I also have to tell it what to write to
the file.

I tell the appender to use
Log::Log4perl::Layout::PatternLayout so I can specify
my own format for the message, and since I want to use that, I need to
specify the pattern. The pattern string is similar to sprintf, but
Log::Log4perl takes care of the % placeholders for me. From the placeholders
in the documentation, I choose the pattern:

[%p] (%F line %L) %m%n

This pattern gives me an error message that includes the error
level (%p for priority), the filename
and line number that logged the message (%F and %L),
the message (%m), and finally a
newline (%n):

[ERROR] (root-logger.pl line 10) I've got something to say!

I have to remember that newline because the module doesn’t make
any assumptions about what I’m doing with the message. There has been a
recurring debate about this, and I think the module does it right: it
does what I say rather than making me adapt to it. I just have to
remember to add newlines myself, either in the format or in the messages
(see Table 13-1).

Table 13-1. PatternLayout placeholders

Placeholder

Description

%c

Category of the message

%C

Package (class) name of the caller

%d

Date-time as YYYY/MM/DD
HH:MM:SS

%F

Filename

%H

Hostname

%l

Shortcut for %c %f
(%L)

%L

Line number

%m

The message

%M

Method or function name

%n

Newline

%p

Priority (e.g., ERROR, DEBUG, INFO)

%P

Process ID

%r

Milliseconds since program start

Persistent Logging

If I’m using this in a persistent program, such as something run under mod_perl,
I don’t need to load the configuration file every time. I can tell
Log::Log4perl not to reload it if it’s already done
it. The init_once method loads the
configuation one time only:

Log::Log4perl::init_once( 'logger.conf' );

Alternatively, I might want Log::Log4perl to
continually check the configuration file and reload it when it changes.
That way, by changing only the configuration file (remember that I
promised I could do this without changing the program), I can affect the
logging behavior while the program is still running. For instance, I
might want to crank up the logging level to see more messages (or send
them to different places). The second argument to init_and_watch is the refresh time, in
seconds:

Log::Log4perl::init_and_watch( 'logger.conf', 30 );

Other Log::Log4perl Features

I’ve only shown the very basics of
Log::Log4perl. It’s much more powerful than that, and
there are already many excellent tutorials out there. Since
Log::Log4perl started life as Log4j, a Java library,
it maintains a lot of the same interface and configuration details, so
you might read the Log4j documentation or tutorials, too.

Having said that, I want to mention one last feature. Since
Log::Log4perl is written in Perl, I can use Perl
hooks in my configuration to dynamically affect the configuration. For
instance, Log::Log4perl::Appender::DBI sends messages
to a database, but I’ll usually need a username and password to write to
the database. I don’t want to store those in a file, so I grab them from
the environment. In this example of an appender, I pull that information
from %ENV. When
Log::Log4perl sees that I’ve wrapped a configuration
value in sub { }, it executes it
as Perl code:[49]

# dbi-logger.conf
log4perl.category = WARN, CSV
log4perl.appender.CSV                 = Log::Log4perl::Appender::DBI
log4perl.appender.CSV.datasource      = DBI:CSV:f_dir=.
log4perl.appender.CSV.username        = sub { $ENV{CSV_USERNAME} }
log4perl.appender.CSV.password        = sub { $ENV{CSV_PASSWORD} }
log4perl.appender.CSV.sql             = 
   insert into csvdb                   
   (pid, level, file, line, message) values (?,?,?,?,?)
   
log4perl.appender.CSV.params.1        = %P    
log4perl.appender.CSV.params.2        = %p    
log4perl.appender.CSV.params.3        = %F
log4perl.appender.CSV.params.4        = %L
log4perl.appender.CSV.usePreparedStmt = 1

log4perl.appender.CSV.layout          = Log::Log4perl::Layout::NoopLayout
log4perl.appender.CSV.warp_message    = 0

My program to use this new logger is the same as before, although
I add some initialization in a BEGIN block to create
the database file if it isn’t already there:

#!/usr/bin/perl
# log4perl-dbi.pl

use Log::Log4perl;

Log::Log4perl::init( 'dbi-logger.conf' );

my $logger = Log::Log4perl->get_logger;

$logger->warn( "I've got something to say!" );

BEGIN { 
        # create the database if it doesn't already exist
        unless( -e 'csvdb' )
                {
                use DBI;

                $dbh = DBI->connect("DBI:CSV:f_dir=.")
                        or die "Cannot connect: " . $DBI::errstr;
                $dbh->do(<<"HERE") or die "Cannot prepare: " . $dbh->errstr();
CREATE TABLE csvdb (
        pid INTEGER, 
        level   CHAR(64),
        file    CHAR(64),
        line    INTEGER,
        message CHAR(64)
        )
HERE

                $dbh->disconnect();
           }
        }

I can do much more complex things with the Perl hooks available in
the configuration files as long as I can write the code to do
it.

Summary

I can easily add logging to my programs with
Log::Log4perl, a Perl version of the Log4j package. I
can use the easy configuration, or specify my own complex configuration.
Once configured, I call subroutines or methods to make a message available
to Log::Log4perl, which decides where to send the
message or if it should ignore it. I just have to send it the
message.

Further Reading

“The log4perl project” at Sourceforge (http://log4perl.sourceforge.net/)
has Log4perl FAQs, tutorials, and other support
resources for the package. You can find answers to most of the basic
questions about using the module, such as “How do I rotate logfiles
automatically?”

Michael Schilli wrote about Log4perl on Perl.com,
“Retire Your Debugger, Log Smartly with Log::Log4perl!” (http://www.perl.com/pub/a/2002/09/11/log4perl.html).

Log4Perl is closely related to Log4j (http://logging.apache.org/log4j/docs/),
the Java logging library, so you do things the same way in each. You can
find good tutorials and documentation for log4j here
that you might be able to apply to
Log4perl, too.

Логирование чего угодно в Perl +11

Программирование, Разработка, Perl


Рекомендация: подборка платных и бесплатных курсов Python — https://katalog-kursov.ru/

Проблема выбора

Для логирования сообщений Перл предлагает несколько готовых решений. Все они, как водится, размещены на CPAN’е. По запросу «log» можно найти кучу модулей на все случаи жизни.

Однако, среди всех этих модулей есть один особенный, называется он Log::Any.

Особенность этого модуля для логирования заключается в том, что он не занимается, собственно, логированием. Модуль Log::Any предоставляет программе (и программисту) универсальное API для обращений к другим модулям, которые занимаются непосредственно логированием.

Если вас мучает проблема выбора способа логирования в Перле — эта статья для вас.

Проблема

Допустим, у вас есть модуль, который загружает из сети некий файл. Вы хотели бы знать, в какое время началась загрузка, сколько она продолжалась и сколько байт было загружено. Вы можете поступить простейшим образом — добавить в модуль строчки:

print "$time Начинаю загрузку файлаn";
# тут выполняется загрузка
print "$time Закончена загрузка файлаn";
print "$time Загружено $size байтn";

Обратите внимание — для того, чтобы вычислить время $time, потребуются еще какие-то дополнительные действия, но я даже не буду заострять на этом внимание, потому что это не главная проблема.

Все будет прекрасно, пока вы запускаете этот скрипт с этим модулем руками из командной строки. Сообщения будут выводиться вам на консоль, вы их прочитаете и узнаете всё, что хотели.

Но в какой-то момент возникнет необходимость сохранять эти сообщения на будущее. Или возникнет необходимость запускать этот скрипт из Крона, а не руками. Или возникнет необходимость писать эти сообщения в базу, для дальнейшего разбора. Ну, или загружаемых файлов будет много, и вам будет сложно читать длинный лог с консоли.

И тогда вы захотите перенаправить вывод лога с консоли куда-нибудь ещё. В файл, в базу, в другую программу, в какой-нибудь веб-сервис по API, к чёрту на рога etc. Тут-то и возникнет проблема — куда же именно и как логировать сообщения?

  • Писать в файл? А вдруг ваш модуль будет использоваться в окружении, где нельзя писать файлы?
  • Писать в базу? А вдруг модуль для работы с базой будет не установлен?
  • Перенаправлять в другую программу? А вдруг пользователь вашего скрипта предпочитает совсем не ту программу, которую выбрали вы?

Есть много отличных модулей для логирования, но все они обладают одним и тем же общим недостатком — этих модулей больше одного. Вам нравится один способ логирования, а пользователю — другой, клиентам — третий, начальству — четвертый. Фатальный недостаток ©.

Решение

Использовать модуль Log::Any.

Log::Any решает описанную выше проблему выбора таким образом, что удовлетворенными оказываются все — программист думает только о том, что он хочет отправить в лог, а потребители лога самостоятельно решают, куда и как записывать полученные сообщения.

Идея этого модуля заключается в том, чтобы разделить процедуру логирования на две отдельные части, которые могут работать независимо друг от друга. При этом, та часть, которая генерирует сообщения, не имеет понятия о том, как и куда эти сообщения будут далее записываться. А часть, которая сообщения куда-то записывает, не имеет понятия о том, откуда эти сообщения взялись и как они были сформированы.

Вот как это работает

Диаграмма работы Log::Any

Пунктирные линии на диаграмме означают подключение модулей через use, а сплошные — направление движения логируемых сообщений.

Отправка сообщений

Для отправки сообщения ваш код (в модуле или в скрипте, не важно) вызывает стандартную функцию, предоставляемую модулем Log::Any:

# Это загрузка модуля Log::Any с одновременным импортом объекта $log, к которому далее нужно будет обращаться для логирования
use Log::Any qw($log);

# А это - уже логирование (кроме метода error есть и другие методы)
$log->error("Что-то случилось при выполнении какой-то задачи");

Указанные выше две строчки — это всё, что нужно, для того, чтобы начать логирование. Но отправленное сообщение пока что не будет никуда записано, так-как мы еще не выбрали, куда конкретно писать лог.

Запись сообщений

Теперь нам нужно решить, куда мы писать лог. Для этого в скрипте нужно воспользоваться одним из адаптеров:

# Этот встроенный адаптер будет просто выводить все сообщения на экран
use Log::Any::Adapter ('Stdout');

# Этот встроенный адаптер будет записывать все сообщения в файл
use Log::Any::Adapter ('File', '/path/to/file.log');

# А этот внешний адаптер будет отправлять все сообщения в отдельный навороченный модуль для логирования Log::Dispatch
use Log::Dispatch;
my $log = Log::Dispatch->new(outputs => [[ ... ]]);
Log::Any::Adapter->set( { category => 'Foo::Baz' }, 'Dispatch', dispatcher => $log );

В комплекте с Log::Any поставляется несколько простых встроенных адаптеров — File, Stdout и Stderr. Как можно догадаться по названию, первый из них записывает сообщения в файл, а два других отправляют сообщения на стандартные выводы.

Помимо встроенных адаптеров на CPAN’е можно найти внешние, такие как Log4perl или Syslog. Внешние адаптеры позволяют писать логи куда угодно — хоть в Твиттер.

А если надо в Фейсбук? Тоже не проблема. Вы можете без особых усилий написать свой собственный адаптер к чему угодно. Создание своего адаптера описано в документации модуля, или вот тут на русском языке.

Я не буду здесь вдаваться в детали написания адаптера, поскольку по ссылкам выше эта задача хорошо описана. Вместо этого я рассмотрю другую задачу — внедрение логирования в уже существующий код.

Логирование уже имеющихся действий

Коннекторы

Если вы пишете код с нуля, вы можете сразу добавить логирование в нужные места. Но если у вас уже есть какой-то объем кода, то добавление функций логирования может потребовать большого объема работы по перекапыванию и модификации имеющегося кода. Вместо этого есть способ добавить логирование, ничего (почти) для этого не делая.

Для этого нужно воспользоватся коннектором — модулем, который подключается к уже имеющемуся коду и сам добавляет в него функции логирования.

Ремарка — термин «коннектор» я выдумал сам, возможно, имеется какое-то другое общепринятое название.

Модули-коннекторы обычно размещаются в пространстве имен Log::Any::For. Есть несколько готовых коннекторов, например, Log::Any::For::DBI или Log::Any::For::LWP.

Написание своих собственных коннекторов не формализовано, так-как сильно зависит от того, к чему, собственно, пишется коннектор. В общем и целом, коннектор работает так:

  • Перехватывается событие, которое нужно логировать. Для этого могут быть использованы разные средства, типа моков или tie.
  • Сообщение о событии отправляется в лог с помощью стандартного вызова $log->method(‘сообщение’).

Использование коннектора происходит так (на примере коннектора LWP):

# Подключаем LWP
use LWP::Simple

# Подключаем коннектор к LWP
use Log::Any::For::LWP;

# И загружаем страничку из сети с помощью функции из LWP
get "http://www.google.com/";

В этом коде не сделано никаких явных действия по отправке сообщений в лог, кроме подключения коннектора. Но, однако, функция get волшебным образом получит логирование и начнет выводить много всяких полезных сообщений.

Логирование предупреждений и исключений

К сожалению, время от времени в программе случаются события, которые не предусмотрены и — по хорошему — не должны случаться. К примеру, внезапно оказалось, что в какой-то функции происходит обращение к неинициализированной переменной, или отваливается коннект к базе, или вообще происходит крах программы. В таких случаях интерпретатор Перла выбросит предупреждение или исключение.

Если такое событие случилось в простом скрипте, который вы запускали из консоли, то соответствующее сообщение появится у вас перед глазами и вы его сразу увидите (хотя, тоже не факт). Если же программа запускается из Крона или работает под управлением веб-сервера, или еще что-нибудь в этом духе, то заметить такое сообщение будет не так-то просто.

Правильное решение — записать такое сообщение в лог. Но как? Ведь в лог пишутся сообщения, которые были явно отправлены туда программистом через объект $log, а варнинги и исключения выбрасывает интерпретатор, который ничего про наше замечательное логирование не знает и валит все свои сообщения просто на STDERR.

Значит, нужно всё, что идет на STDERR, принудительно перенаправить в лог.

Для решения этой задачи я не нашел подходящего коннектора на CPAN’е, поэтому написал свой — Log::Any::For::Std. Этот коннектор отправляет в лог все возможные сообщения интепретатора, на любом этапе исполнения программы.

Для перехвата STDERR иcпользуется функция tie:

tie *STDERR, __PACKAGE__;

Эта конструкция заворачивает абсолютно всё, что отправляется на STDERR, в нужный нам пакет, а в нем уже не составляет труда перенаправить сообщения в лог с помощью Log::Any.

При желании вы можете реализовать любой другой коннектор для перехвата предупреждений и исключений (или вообще можете их не перехватывать).

Фильтрация сообщений

Обстоятельства могут сложиться так, что имеющийся код уже выводит какие-то сообщения. Например, у меня есть большой проект с легаси-кодом, в котором всё логирование сделано так:

print STDERR "$time --- $login --- $pid --- некое сообщениеn";

Как можно видеть, здесь все сообщения отправляются на STDERR, а в тексте сообщений имеются всякие переменные, разделители, да плюс ещё перевод строки. Вдобавок, хоть это и не видно на глаз, все сообщения написаны без использования utf8.

Перенаправление сообщений с STDERR в лог легко решается с помощью коннектора Log::Any::For::Std, а вот лишний мусор из текста сообщения придется убирать отдельно. Для этого при подключении модуля Log::Any нужно включить фильтрацию.

Делается это примерно так:

use Log::Any '$log', filter => sub { my $msg = $_[2]; utf8::decode($msg); return $msg };

Каждое сообщение, отправляемое в лог с помощью $log->method(), будет пропускаться через функцию, указанную в аргументе filter. Переменная $_[2] в этой функции содержит отправляемое сообщение. Если вы хотите что-то сделать с сообщением, то вы должны взять его из этой переменной, модифицировать и возвратить. Возвращенное значение будет записано в лог.

К примеру, в приведенном выше коде текст сообщения приводится к utf8.

Пример скрипта

Давайте соберем всё это вместе в скрипте test.pl:

#!/usr/bin/perl

use strict;
use warnings;

use Log::Any '$log', filter => sub { my $msg = $_[2]; $msg =~ s/привет/прЕвеД/; return $msg };
use Log::Any::Adapter ('Stdout');
use Log::Any::For::Std;

print "Это просто сообщениеn";

$log->info("А это сообщение в лог");

$log->info("Тут на слове привет сработает фильтрация");

Module::func();

warn "Предупреждение тоже окажется в логе";

die "И даже исключение можно завернуть в лог";

# Модуль
package Module;

use Log::Any '$log';

sub func {
    $log->info("Сообщение из модуля окажется в логе");
}

Запускаем и видим следующее:

$ ./test.pl 
Это просто сообщение
А это сообщение в лог
Тут на слове прЕвеД сработает фильтрация
Сообщение из модуля окажется в логе
Предупреждение тоже окажется в логе at ./test.pl line 18.
И даже исключение можно завернуть в лог at ./test.pl line 20.

Все сообщения будут выведены на консоль, но не верьте глазам своим — только первая строчка является обычным выводом, всё остальное — это лог. Просто этот лог выведен на консоль.

А что, если теперь нам вдруг захочется отправить лог не на консоль, а в файл? С модулем Log::Any нет ничего проще:

# Достаточно сменить адаптер с этого
# use Log::Any::Adapter ('Stdout');

# На этот
use Log::Any::Adapter ('File', 'file.log');

Запускаем и видим:

$ ./test.pl 
Это просто сообщение

Как и ожидалось, на консоль будет выведен только print.

А вот куда делось всё остальное:

$ cat file.log 
[Fri Jun 19 17:25:44 2015] А это сообщение в лог
[Fri Jun 19 17:25:44 2015] Тут на слове прЕвеД сработает фильтрация
[Fri Jun 19 17:25:44 2015] Сообщение из модуля окажется в логе
[Fri Jun 19 17:25:44 2015] Предупреждение тоже окажется в логе at ./test.pl line 18.
[Fri Jun 19 17:25:44 2015] И даже исключение можно завернуть в лог at ./test.pl line 20.

Резюме

  • Модуль Log::Any позволяет добавить в ваши программы и модули гибкое логирование, которое потом не потребуется переделывать при смене способа сохранения лога
  • Адаптеры Log::Any::Adapter позволяют адаптировать вашу программу к любому способу сохранения лога
  • Коннекторы Log::Any::For позволяют подключить логирование к любому источнику сообщений
: ===> gnu/usr.bin/perl cd /w1/o/cur/src/gnu/usr.bin/perl/obj && PATH=»/bin:/usr/bin:/sbin:/usr/sbin» exec /bin/sh /w1/o/cur/src/gnu/usr.bin/perl/Configure -dse -Dopenbsd_distribution=defined -Dmksymlinks (I see you are using the Korn shell. Some ksh’s blow up on Configure, mainly on older exotic systems. If yours does, try the Bourne shell instead.) Sources for perl5 found in «/w1/o/cur/src/gnu/usr.bin/perl». First let’s make sure your kit is complete. Checking… Locating common programs… Checking compatibility between /bin/echo and builtin echo (if any)… Symbolic links are supported. Checking how to test for symbolic links… You can test for symbolic links with ‘test -h’. Creating the symbolic links… Checking for cross-compile No targethost for running compiler tests against defined, running locally Good, your tr supports [:lower:] and [:upper:] to convert case. Using [:upper:] and [:lower:] to convert case. aix esix4 lynxos sco_2_3_2 aix_3 fps midnightbsd sco_2_3_3 aix_4 freebsd minix sco_2_3_4 altos486 freemint mips solaris_2 amigaos gnu mirbsd stellar atheos gnukfreebsd mpc sunos_4_0 aux_3 gnuknetbsd ncr_tower sunos_4_1 bitrig greenhills netbsd super-ux bsdos haiku newsos4 svr4 catamount hpux nonstopux svr5 convexos i386 openbsd ti1500 cxux interix opus ultrix_4 cygwin irix_4 os2 umips darwin irix_5 os390 unicos dcosx irix_6 os400 unicosmk dec_osf irix_6_0 posix-bc unisysdynix dos_djgpp irix_6_1 qnx utekv dragonfly isc riscos uwin dynix isc_2 sco vos dynixptx linux-android sco_2_3_0 epix linux sco_2_3_1 Which of these apply, if any? [openbsd] Operating system name? [openbsd] Operating system version? [6.9] Installation prefix to use? (~name ok) [/usr] AFS does not seem to be running… What installation prefix should I use for installing files? (~name ok) [/usr] Getting the current patchlevel… Build a threading Perl? [n] Build Perl for multiplicity? [n] Use which C compiler? [cc] Checking for GNU cc in disguise and/or its version number… Now, how can we feed standard input to your C preprocessor… Directories to use for library searches? [/usr/lib /usr/lib] What is the file extension used for shared libraries? [so] Make shared library basenames unique? [n] Build Perl for SOCKS? [n] Try to use long doubles if available? [n] Checking for optional libraries… What libraries to use? [-lm -lc] What optimizer/debugger flag should be used? [-O2] Any additional cc flags? [-DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong] Let me guess what the preprocessor flags are… Any additional ld flags (NOT including libraries)? [-Wl,-E -fstack-protector-strong] Checking your choice of C compiler and flags for coherency… Checking to see how big your integers are… Checking to see if you have long long… Checking to see how big your long longs are… Computing filename position in cpp output for #include directives… <inttypes.h> found. Checking to see if you have int64_t… Checking which 64-bit integer type we could use… We could use ‘long long’ for 64-bit integers. Try to use 64-bit integers, if available? [n] Try to use maximal 64-bit support, if available? [n] Checking for GNU C Library… Shall I use /usr/bin/nm to extract C symbols from the libraries? [y] Where is your C library? [/usr/lib/libc.a] Extracting names from the following files for later perusal: /usr/lib/libc.a /usr/lib/libm.so.10.1 This may take a while….done. Checking for C++… Checking to see how big your double precision numbers are… Checking to see if you have long double… ldexpl() found. Checking to see how big your long doubles are… Checking the kind of long doubles you have… Your long doubles are doubles. What is your architecture name [OpenBSD.m88k-openbsd] Add the Perl API version to your archname? [n] Pathname where the public executables will reside? (~name ok) [/usr/bin] Use relocatable @INC? [n] Pathname where the private library files will reside? (~name ok) [/usr/lib/perl5/5.32.1] Where do you want to put the public architecture-dependent libraries? (~name ok) [/usr/lib/perl5/5.32.1/OpenBSD.m88k-openbsd] Other username to test security of setuid scripts with? [none] Well, the recommended value *is* secure. Does your kernel have *secure* setuid scripts? [y] Installation prefix to use for add-on modules and utilities? (~name ok) [/usr/local] Pathname for the site-specific library files? (~name ok) [/usr/local/lib/perl5/site_perl/5.32.1] List of earlier versions to include in @INC? [none] <malloc/malloc.h> NOT found. <malloc.h> NOT found. Checking to see how big your pointers are… Do you wish to wrap malloc calls to protect against potential overflows? [y] Do you wish to attempt to use the malloc that comes with perl5? [n] Your system wants malloc to return ‘void *’, it would seem. Your system uses void free(), it would seem. Pathname for the site-specific architecture-dependent library files? (~name ok) [/usr/local/lib/perl5/site_perl/5.32.1/OpenBSD.m88k-openbsd] Do you want to configure vendor-specific add-on directories? [n] Colon-separated list of additional directories for perl to search? [none] Support DTrace if available? [n] Install any extra modules (y or n)? [n] Directory for the main Perl5 html pages? (~name ok) [none] Directory for the Perl5 module html pages? (~name ok) [none] dlopen() found. <unistd.h> found. Do you wish to use dynamic loading? [y] Source file to use for dynamic loading [ext/DynaLoader/dl_dlopen.xs] Any special flags to pass to cc -c to compile shared library modules? [-DPIC -fpic ] What command should be used to create dynamic libraries? [cc] Any special flags to pass to cc to create a dynamically loaded library? [-shared -fpic -fstack-protector-strong] Any special flags to pass to cc to use dynamic linking? [none] ld supports scripting Build a shared libperl.so (y/n) [y] What name do you want to give to the shared libperl? [libperl.so.22.0] Adding -Wl,-R/usr/lib/perl5/5.32.1/OpenBSD.m88k-openbsd/CORE to the flags passed to cc so that the perl executable will find the installed shared libperl.so.22.0. System manual is in /usr/share/man/man1. Where do the main Perl5 manual pages (source) go? (~name ok) [none] You can have filenames longer than 14 characters. Where do the perl5 library man pages (source) go? (~name ok) [none] Figuring out host name… Your host name appears to be «aurora.in.nk-home.net». Right? [y] What is your domain name? [.in.nk-home.net] What is your e-mail address? [aoyama@aurora.in.nk-home.net] Perl administrator e-mail address [aoyama@aurora.in.nk-home.net] Do you want to use a version number suffix for installed binaries? [n] What shall I put after the #! to start up perl («none» to not use #!)? [/usr/bin/perl] Where do you keep publicly executable scripts? (~name ok) [/usr/bin] Pathname where the add-on public executables should be installed? (~name ok) [/usr/local/bin] Pathname where the site-specific html pages should be installed? (~name ok) [none] Pathname where the site-specific library html pages should be installed? (~name ok) [none] Pathname where the site-specific manual pages should be installed? (~name ok) [none] Pathname where the site-specific library manual pages should be installed? (~name ok) [none] Pathname where add-on public executable scripts should be installed? (~name ok) [/usr/local/bin] backtrace() NOT found. Use the «fast stdio» if available? [n] off_t found. Checking to see how big your file offsets are… fpos_t found. Checking the size of fpos_t… qgcvt() NOT found. Checking the kind of doubles you have… You have IEEE 754 64-bit big endian doubles. Checking how to print long doubles… gconvert NOT found. gcvt() found. I’ll use gcvt to convert floats into a string. fwalk() NOT found. accept4() found. access() found. <unistd.h> defines the *_OK access constants. accessx() NOT found. acosh() found. aintl() NOT found. alarm() found. ctime64() NOT found. localtime64() NOT found. gmtime64() NOT found. mktime64() NOT found. difftime64() NOT found. asctime64() NOT found. <pthread.h> found. <sys/types.h> found. <sys/select.h> found. Testing to see if we should include <sys/time.h>. We’ll include <sys/time.h>. Checking to see if your struct tm has tm_zone field… Checking to see if your struct tm has tm_gmtoff field… asctime_r() found. asinh() found. atanh() found. atolf() NOT found. atoll() found. Checking whether your compiler can handle __attribute__((format)) … Checking whether your compiler allows __printf__ format to be null … Checking whether your compiler can handle __attribute__((malloc)) … Checking whether your compiler can handle __attribute__((nonnull(1))) … Checking whether your compiler can handle __attribute__((noreturn)) … Checking whether your compiler can handle __attribute__((pure)) … Checking whether your compiler can handle __attribute__((unused)) … Checking whether your compiler can handle __attribute__((deprecated)) … Checking whether your compiler can handle __attribute__((warn_unused_result)) … Checking whether your compiler can handle __attribute__((always_inline)) … getpgrp() found. You have to use getpgrp() instead of getpgrp(pid). setpgrp() found. You have to use setpgrp(pid,pgrp) instead of setpgrp(). Checking whether your compiler can handle __builtin_add_overflow … Checking whether your compiler can handle __builtin_sub_overflow … Checking whether your compiler can handle __builtin_mul_overflow … Checking whether your compiler can handle __builtin_choose_expr … Checking whether your compiler can handle __builtin_expect … Checking for C99 variadic macros. You have C99 variadic macros. You have void (*signal())(). Checking whether your C compiler can cast large floats to int32. Checking whether your C compiler can cast negative float to unsigned. cbrt() found. chown() found. chroot() found. chsize() NOT found. class() NOT found. clearenv() NOT found. Hmm… Looks like you have Berkeley networking support. socketpair() found. Checking the availability sa_len in the sock struct … Checking the availability struct sockaddr_in6 … Checking the availability struct sockaddr_storage … Checking the availability sin6_scope_id in struct sockaddr_in6 … Checking the availability struct ip_mreq … Checking the availability struct ip_mreq_source … Checking the availability struct ipv6_mreq … Checking the availability struct ipv6_mreq_source … Checking the availability of certain socket constants… <sys/uio.h> found. Checking to see if your system supports struct cmsghdr… copysign() found. copysignl() found. crypt() found. <crypt.h> NOT found. crypt_r() NOT found. ctermid() found. ctermid_r() NOT found. ctime_r() found. cuserid() NOT found. dbmclose() NOT found. difftime() found. <dirent.h> found. Your directory entries are struct dirent. Good, your directory entry keeps length information in d_namlen. Checking to see if DIR has a dd_fd member variable <sys/dir.h> found. <sys/ndir.h> NOT found. dirfd() found. dladdr() found. dlerror() found. <dlfcn.h> found. What is the extension of dynamically loaded modules [so] Checking whether your dlsym() needs a leading underscore … dlsym doesn’t need a leading underscore. drand48_r() NOT found. dup2() found. dup3() found. <xlocale.h> NOT found. newlocale() found. Hmm. Based on the hints in hints/openbsd.sh, the recommended value for $d_newlocale on this machine was «undef»! Keep the recommended value? [y] freelocale() found. uselocale() found. duplocale() found. querylocale() NOT found. eaccess() NOT found. endgrent() found. <grp.h> found. endgrent_r() NOT found. endhostent() found. <netdb.h> found. endhostent_r() NOT found. endnetent() found. endnetent_r() NOT found. endprotoent() found. endprotoent_r() found. endpwent() found. <pwd.h> found. endpwent_r() NOT found. endservent() found. endservent_r() found. <sys/file.h> defines the O_* constants… and you have the 3 argument form of open(). <sys/file.h> found. We’ll be including <sys/file.h>. <fcntl.h> found. We don’t need to include <fcntl.h> if we include <sys/file.h>. fork() found. pipe() found. Figuring out the flag used by open() for non-blocking I/O… Let’s see what value errno gets from read() on a O_NONBLOCK file… erf() found. erfc() found. exp2() found. expm1() found. Checking how std your stdio is… Checking to see what happens if we set the stdio ptr… Increasing ptr in your stdio leaves cnt unchanged. Good. You seem to have ‘fast stdio’ to directly manipulate the stdio buffers. fchdir() found. fchmod() found. openat() found. unlinkat() found. renameat() found. linkat() found. fchmodat() found. fchown() found. fcntl() found. Well, your system knows about the normal fd_set typedef… and you have the normal fd_set macros (just as I’d expect). fdclose() NOT found. fdim() found. fegetround() found. fgetpos() found. finite() found. finitel() NOT found. flock() found. fma() found. fmax() found. fmin() found. fp_class() NOT found. Checking to see if you have fpclassify… fp_classify() NOT found. fp_classl() NOT found. pathconf() found. fpathconf() found. fpclass() NOT found. fpclassl() NOT found. fpgetround() found. Checking to see if you have fpos64_t… frexpl() found. <sys/param.h> found. <sys/mount.h> found. Checking to see if your system supports struct fs_data… fseeko() found. fsetpos() found. fstatfs() found. statvfs() found. fstatvfs() found. fsync() found. ftello() found. Checking if you have a working futimes() Yes, you have A working gai_strerror() found. <ndbm.h> found. <gdbm/ndbm.h> NOT found. <gdbm-ndbm.h> NOT found. dbm_open() found. Checking if your <ndbm.h> uses prototypes… getaddrinfo() found. getcwd() found. getespwnam() NOT found. getfsstat() found. getgrent() found. getgrent_r() NOT found. getgrgid_r() found. getgrnam_r() found. gethostbyaddr() found. gethostbyname() found. gethostent() found. gethostname() found. uname() found. Shall I ignore gethostname() from now on? [n] gethostbyaddr_r() NOT found. gethostbyname_r() NOT found. gethostent_r() NOT found. getitimer() found. getlogin() found. getlogin_r() found. getmnt() NOT found. getmntent() NOT found. getnameinfo() found. getnetbyaddr() found. getnetbyname() found. getnetent() found. getnetbyaddr_r() NOT found. getnetbyname_r() NOT found. getnetent_r() NOT found. getpagesize() found. getprotobyname() found. getprotobynumber() found. getprotoent() found. getpgid() found. getpgrp2() NOT found. getppid() found. getpriority() found. getprotobyname_r() found. getprotobynumber_r() found. getprotoent_r() found. getprpwnam() NOT found. getpwent() found. getpwent_r() NOT found. getpwnam_r() found. getpwuid_r() found. getservbyname() found. getservbyport() found. getservent() found. getservbyname_r() found. getservbyport_r() found. getservent_r() found. getspnam() NOT found. <shadow.h> NOT found. getspnam_r() NOT found. gettimeofday() found. gmtime_r() found. hasmntopt() NOT found. <netinet/in.h> found. <arpa/inet.h> found. htonl() found. hypot() found. ilogb() found. ilogbl() found. inet_aton() found. inet_ntop() found. inet_pton() found. isascii() found. isblank() found. Checking to see if you have isfinite… isfinitel() NOT found. Checking to see if you have isinf… isinfl() NOT found. Checking to see if you have isless… Checking to see if you have isnan… isnanl() NOT found. Checking to see if you have isnormal… j0() found. j0l() NOT found. killpg() found. localeconv() found. lchown() found. LDBL_DIG found. lgamma() found. lgamma_r() found. Checking to see if your libm supports _LIB_VERSION… No, it does not (probably harmless) link() found. llrint() found. llrintl() found. llround() found. llroundl() found. localeconv_l() NOT found. localtime_r() found. lockf() found. log1p() found. log2() found. logb() found. lrint() found. lrintl() found. lround() found. lroundl() found. lstat() found. madvise() found. malloc_size() NOT found. malloc_good_size() NOT found. malloc_usable_size() NOT found. mblen() found. mbrlen() found. mbrtowc() found. mbstowcs() found. mbtowc() found. memmem() found. memrchr() found. mkdir() found. mkdtemp() found. mkfifo() found. mkostemp() found. mkstemp() found. mkstemps() found. mktime() found. <sys/mman.h> found. mmap() found. and it returns (void *). sqrtl() found. scalbnl() found. truncl() found. modfl() found. mprotect() found. msgctl() found. msgget() found. msgsnd() found. msgrcv() found. You have the full msg*(2) library. Checking to see if your system supports struct msghdr… msync() found. munmap() found. nan() found. nanosleep() found. nearbyint() found. nextafter() found. nexttoward() found. nice() found. <langinfo.h> found. nl_langinfo() found. <quadmath.h> NOT found. Choosing the C types to be used for Perl’s internal types… Checking how many bits of your UVs your NVs can preserve… Checking to find the largest integer value your NVs can hold… The largest integer your NVs can preserve is equal to 256.0*256.0*256.0*256.0*256.0*256.0*2.0*2.0*2.0*2.0*2.0 Checking whether NV 0.0 is all bits zero in memory… 0.0 is represented as all bits zero in memory Checking to see if you have off64_t… pause() found. pipe2() found. poll() found. prctl() NOT found. readlink() found. vfork() found. Do you still want to use vfork()? [y] pthread_attr_setscope() NOT found. Checking to see if you have ptrdiff_t… random_r() NOT found. readdir() found. seekdir() found. telldir() found. rewinddir() found. readdir64_r() NOT found. readdir_r() found. readv() found. recvmsg() found. regcomp() found. remainder() found. remquo() found. rename() found. rint() found. rmdir() found. round() found. scalbn() found. select() found. semctl() found. semget() found. semop() found. You have the full sem*(2) library. You have union semun in <sys/sem.h>. You can use union semun for semctl IPC_STAT. You can also use struct semid_ds* for semctl IPC_STAT. sendmsg() found. setegid() found. seteuid() found. setgrent() found. setgrent_r() NOT found. sethostent() found. sethostent_r() NOT found. setitimer() found. setlinebuf() found. <locale.h> found. <wctype.h> found. towupper() found. Your system has setlocale()… and it seems sane, but accepts any locale name as valid setlocale_r() NOT found. setnetent() found. setnetent_r() NOT found. setprotoent() found. setpgid() found. setpgrp2() NOT found. setpriority() found. setproctitle() found. setprotoent_r() found. setpwent() found. setpwent_r() NOT found. setregid() found. setresgid() found. setreuid() found. setresuid() found. setrgid() NOT found. setruid() NOT found. setservent() found. setservent_r() found. setsid() found. setvbuf() found. shmctl() found. shmget() found. shmat() found. and it returns (void *). shmdt() found. You have the full shm*(2) library. sigaction() found. pid_t found. Checking if your siginfo_t has si_errno field… Checking if your siginfo_t has si_pid field… Checking if your siginfo_t has si_uid field… Checking if your siginfo_t has si_addr field… Checking if your siginfo_t has si_status field… Checking if your siginfo_t has si_band field… Checking if your siginfo_t has si_value field… Checking if your siginfo_t has si_fd field… <sunmath.h> NOT found. Checking to see if you have signbit() available to work on double… Yes. sigprocmask() found. POSIX sigsetjmp found. snprintf() found. vsnprintf() found. sockatmark() found. socks5_init() NOT found. srand48_r() NOT found. srandom_r() NOT found. stat() found. <sys/stat.h> found. Checking to see if your struct stat has st_blocks field… <sys/vfs.h> NOT found. <sys/statfs.h> NOT found. Checking to see if your system supports struct statfs… Checking to see if your struct statfs has f_flags field… Your compiler supports static __inline__. Checking how to access stdio streams by file descriptor number… You can access stdio streams by file descriptor number by the __sF array. strcoll() found. strerror_l() found. strerror_r() found. strftime() found. strlcat() found. strlcpy() found. strnlen() found. strtod() found. strtod_l() NOT found. strtol() found. strtold() found. strtold_l() NOT found. strtoll() found. strtoq() found. strtoul() found. strtoull() found. strtouq() found. strxfrm() found. symlink() found. syscall() found. sysconf() found. system() found. tcgetpgrp() found. tcsetpgrp() found. tgamma() found. Since threads aren’t selected, we won’t bother looking for nl_langinfo_l() time() found. time_t found. timegm() found. <sys/times.h> found. times() found. clock_t found. tmpnam_r() NOT found. towlower() found. trunc() found. truncate() found. ttyname_r() found. tzname[] found. (Testing for character data alignment may crash the test. That’s okay.) It seems that you must access character data in an aligned manner. ualarm() found. umask() found. unordered() NOT found. unsetenv() found. usleep() found. ustat() NOT found. closedir() found. Checking whether closedir() returns a status… wait4() found. waitpid() found. wcrtomb() found. A working wcscmp() found. wcstombs() found. A working wcsxfrm() found. wctomb() found. writev() found. Checking alignment constraints… Doubles must be aligned on a how-many-byte boundary? [8] Checking how long a character is (in bits)… What is the length of a character (in bits)? [8] Checking to see how your cpp does stuff like concatenate tokens… Oh! Smells like ANSI’s been here. <db.h> found. Checking Berkeley DB version … Looks OK. Checking return type needed for hash for Berkeley DB … Checking return type needed for prefix for Berkeley DB … Exclude . from @INC by default? [y] Checking the kind of infinities and nans you have… (The following tests may crash. That’s okay.) Checking how many mantissa bits your doubles have… Checking how many mantissa bits your long doubles have… Checking how many mantissa bits your NVs have… Using our internal random number implementation… Determining whether or not we are on an EBCDIC system… Nope, no EBCDIC, probably ASCII or some ISO Latin. Or UTF-8. Checking how to flush all pending stdio output… Your fflush(NULL) works okay for output streams. Let’s see if it clobbers input pipes… fflush(NULL) seems to behave okay with input streams. Checking the size of gid_t… Checking the sign of gid_t… Checking how to print 64-bit integers… Checking the format strings to be used for Perl’s internal types… Checking the format string to be used for gids… getgroups() found. setgroups() found. What type pointer is the second argument to getgroups() and setgroups()? [gid_t] Checking if your /usr/bin/make program sets $(MAKE)… mode_t found. It seems that you don’t need va_copy(). size_t found. What is the type for the 1st argument to gethostbyaddr? [char *] What is the type for the 2nd argument to gethostbyaddr? [size_t] What pager is used on your system? [/usr/bin/less -R] Checking how to generate random libraries on your machine… Your select() operates on 32 bits at a time. Generating a list of signal names and numbers… Checking the size of size_t… Checking to see if you have socklen_t… <socks.h> NOT found. I’ll be using ssize_t for functions returning a byte count. Checking the size of st_ino… Checking the sign of st_ino… Your stdio uses signed chars. Checking the size of uid_t… Checking the sign of uid_t… Checking the format string to be used for uids… Determining whether we can use sysctl with KERN_PROC_PATHNAME to find executing program… I’m unable to compile the test program. I’ll assume no sysctl with KERN_PROC_PATHNAME here. Determining whether we can use _NSGetExecutablePath to find executing program… I’m unable to compile the test program. I’ll assume no _NSGetExecutablePath here. Which compiler compiler (yacc) shall I use? [yacc] <bfd.h> NOT found. <execinfo.h> NOT found. <fenv.h> found. <fp.h> NOT found. <fp_class.h> NOT found. <gdbm.h> NOT found. <ieeefp.h> found. <libutil.h> NOT found. <mntent.h> NOT found. <net/errno.h> NOT found. <netinet/tcp.h> found. <poll.h> found. <prot.h> NOT found. Guessing which symbols your C compiler and preprocessor define… You seem not to have gcc 4.* or later, not adding -D_FORTIFY_SOURCE. tcsetattr() found. You have POSIX termios.h… good! <stdbool.h> found. <stdint.h> found. <sys/access.h> NOT found. <sys/filio.h> found. <sys/ioctl.h> found. You have socket ioctls defined in <sys/sockio.h>. <syslog.h> found. <sys/mode.h> NOT found. <sys/poll.h> found. <sys/resource.h> found. <sys/security.h> NOT found. <sys/statvfs.h> found. <sys/un.h> found. <sys/utsname.h> found. <sys/wait.h> found. <ustat.h> NOT found. <utime.h> found. <vfork.h> NOT found. <wchar.h> found. Looking for extensions… What extensions do you wish to load dynamically? [B Compress/Raw/Bzip2 Compress/Raw/Zlib Cwd DB_File Data/Dumper Devel/PPPort Devel/Peek Digest/MD5 Digest/SHA Encode Fcntl File/DosGlob File/Glob Filter/Util/Call Hash/Util Hash/Util/FieldHash I18N/Langinfo IO IPC/SysV List/Util MIME/Base64 Math/BigInt/FastCalc NDBM_File Opcode OpenBSD/MkTemp OpenBSD/Pledge OpenBSD/Unveil POSIX PerlIO/encoding PerlIO/mmap PerlIO/scalar PerlIO/via SDBM_File Socket Storable Sys/Hostname Sys/Syslog Term/ReadKey Time/HiRes Time/Piece Unicode/Collate Unicode/Normalize XS/APItest XS/Typemap attributes mro re threads threads/shared] What extensions do you wish to load statically? [none] I see a config.over file. Do you wish to load it? [y] Stripping down executable paths… Creating config.sh… Doing variable substitutions on .SH files… Extracting config.h (with variable substitutions) cflags.SH: Adding -std=c89. cflags.SH: Adding -Wextra. cflags.SH: Adding -Wwrite-strings. cflags.SH: cc = cc cflags.SH: ccflags = -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong cflags.SH: stdflags = -std=c89 cflags.SH: optimize = -O2 cflags.SH: warn = -Wall -Wextra -Wwrite-strings Extracting cflags (with variable substitutions) Extracting config.h (with variable substitutions) Extracting makedepend (with variable substitutions) Extracting Makefile (with variable substitutions) Extracting myconfig (with variable substitutions) Extracting pod/Makefile (with variable substitutions) Extracting Policy.sh (with variable substitutions) Extracting runtests (with variable substitutions) Run make depend now? [y] cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic generate_uudmap.c cc -o generate_uudmap -Wl,-E -fstack-protector-strong generate_uudmap.o -lm -lc ./generate_uudmap uudmap.h bitcount.h mg_data.h sh ./makedepend MAKE=»make» cflags rm -f opmini.c rm -f perlmini.c cp op.c opmini.c cp perl.c perlmini.c echo av.c scope.c op.c doop.c doio.c dump.c gv.c hv.c mg.c reentr.c mro_core.c perl.c perly.c pp.c pp_hot.c pp_ctl.c pp_sys.c regcomp.c regexec.c utf8.c sv.c taint.c toke.c util.c deb.c run.c universal.c pad.c globals.c keywords.c perlio.c perlapi.c numeric.c mathoms.c locale.c pp_pack.c pp_sort.c caretx.c dquote.c time64.c miniperlmain.c opmini.c perlmini.c | tr ‘ ‘ ‘n’ >.clist Finding dependencies for av.o Finding dependencies for scope.o Finding dependencies for op.o Finding dependencies for doop.o Finding dependencies for doio.o Finding dependencies for dump.o Finding dependencies for gv.o Finding dependencies for hv.o Finding dependencies for mg.o Finding dependencies for reentr.o Finding dependencies for mro_core.o Finding dependencies for perl.o Finding dependencies for perly.o Finding dependencies for pp.o Finding dependencies for pp_hot.o Finding dependencies for pp_ctl.o Finding dependencies for pp_sys.o Finding dependencies for regcomp.o Finding dependencies for regexec.o Finding dependencies for utf8.o Finding dependencies for sv.o Finding dependencies for taint.o Finding dependencies for toke.o Finding dependencies for util.o Finding dependencies for deb.o Finding dependencies for run.o Finding dependencies for universal.o Finding dependencies for pad.o Finding dependencies for globals.o Finding dependencies for keywords.o Finding dependencies for perlio.o Finding dependencies for perlapi.o Finding dependencies for numeric.o Finding dependencies for mathoms.o Finding dependencies for locale.o Finding dependencies for pp_pack.o Finding dependencies for pp_sort.o Finding dependencies for caretx.o Finding dependencies for dquote.o Finding dependencies for time64.o Finding dependencies for miniperlmain.o Finding dependencies for opmini.o Finding dependencies for perlmini.o Updating makefile… Now you must run ‘make’. If you compile perl5 on a different machine or from a different object directory, copy the Policy.sh file from this object directory to the new one before you run Configure — this will help you with most of the policy defaults. cd /w1/o/cur/src/gnu/usr.bin/perl && exec make -f Makefile.bsd-wrapper1 perl.build cd /w1/o/cur/src/gnu/usr.bin/perl/obj && exec make rm -f pod/perl5321delta.pod /bin/ln -s perldelta.pod pod/perl5321delta.pod echo @`sh cflags «optimize=’-O2′» perlmini.o` -DPIC -fpic -DPERL_IS_MINIPERL -DPERL_EXTERNAL_GLOB perlmini.c echo @`sh cflags «optimize=’-O2′» opmini.o` -DPIC -fpic -DPERL_IS_MINIPERL -DPERL_EXTERNAL_GLOB opmini.c @cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic -DPERL_IS_MINIPERL -DPERL_EXTERNAL_GLOB perlmini.c @cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic -DPERL_IS_MINIPERL -DPERL_EXTERNAL_GLOB opmini.c cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic miniperlmain.c In file included from perl.h:6161, from op.c:163: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression In file included from perl.h:6161, from perl.c:38: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression In file included from perl.h:6161, from miniperlmain.c:57: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic time64.c In file included from perl.h:6161, from time64.c:44: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression time64.c: In function `Perl_localtime64_r’: time64.c:482: warning: `orig_year’ might be used uninitialized in this function cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic dquote.c In file included from perl.c:3944: intrpvar.h: In function `S_init_interp’: intrpvar.h:813: warning: `Perl_sv_nounlocking’ is deprecated (declared at proto.h:3526) In file included from perl.h:6161, from dquote.c:10: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic caretx.c In file included from perl.h:6161, from caretx.c:32: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic pp_sort.c cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic pp_pack.c op.c: In function `S_pmtrans’: op.c:7037: warning: `r_cp’ might be used uninitialized in this function op.c:7037: warning: `t_cp’ might be used uninitialized in this function In file included from perl.h:6161, from pp_sort.c:31: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression In file included from perl.h:6161, from pp_pack.c:33: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic locale.c In file included from perl.h:6161, from locale.c:49: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression inline.h: At top level: locale.c:1871: warning: `S_new_collate’ defined but not used locale.c:1369: warning: `S_new_numeric’ defined but not used locale.c:1327: warning: `S_set_numeric_radix’ defined but not used cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic mathoms.c In file included from perl.h:6161, from mathoms.c:66: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression mathoms.c: In function `Perl_sv_pvbyten’: mathoms.c:470: warning: `Perl_sv_pvn’ is deprecated (declared at mathoms.c:387) mathoms.c: In function `Perl_sv_pvutf8n’: mathoms.c:506: warning: `Perl_sv_pvn’ is deprecated (declared at mathoms.c:387) cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic numeric.c cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic perlapi.c In file included from perl.h:6161, from numeric.c:30: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression In file included from perl.h:6161, from perlapi.c:28: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic perlio.c cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic keywords.c In file included from perl.h:6161, from perlio.c:43: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression In file included from perl.h:6161, from keywords.c:9: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic globals.c cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic pad.c In file included from perl.h:5590, from globals.c:32: intrpvar.h:813: warning: `Perl_sv_nounlocking’ is deprecated (declared at proto.h:3526) In file included from perl.h:6161, from pad.c:150: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression In file included from perl.h:6161, from globals.c:32: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic universal.c cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic run.c In file included from perl.h:6161, from universal.c:30: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression In file included from perl.h:6161, from run.c:26: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic deb.c cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic util.c In file included from perl.h:6161, from deb.c:25: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic toke.c In file included from perl.h:6161, from util.c:26: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression In file included from perl.h:6161, from toke.c:40: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic taint.c In file included from perl.h:6161, from taint.c:24: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic sv.c cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic utf8.c In file included from perl.h:6161, from sv.c:32: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression In file included from perl.h:6161, from utf8.c:33: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic regexec.c In file included from perl.h:6161, from regexec.c:75: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression sv.c: In function `Perl_sv_setpviv_mg’: sv.c:10768: warning: `Perl_sv_setpviv’ is deprecated (declared at sv.c:10738) sv.c: In function `S_format_hexfp’: sv.c:11629: warning: unused parameter `in_lc_numeric’ cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic regcomp.c toke.c: At top level: toke.c:9807: warning: `S_parse_ident’ declared inline after being called regexec.c: In function `S_regmatch’: regexec.c:6864: warning: comparison between signed and unsigned regexec.c:6874: warning: comparison between signed and unsigned In file included from perl.h:6161, from regcomp.c:132: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression toke.c: In function `Perl_scan_num’: toke.c:11404: warning: `shift’ might be used uninitialized in this function toke.c:11636: warning: `b’ might be used uninitialized in this function regexec.c:6442: warning: `folder’ might be used uninitialized in this function regexec.c:6443: warning: `fold_array’ might be used uninitialized in this function cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic pp_sys.c In file included from perl.h:6161, from pp_sys.c:31: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression regexec.c: In function `S_regrepeat’: regexec.c:9757: warning: comparison between signed and unsigned pp_sys.c: In function `Perl_pp_stat’: pp_sys.c:2949: warning: comparison of unsigned expression < 0 is always false cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic pp_ctl.c In file included from perl.h:6161, from pp_ctl.c:35: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression pp_ctl.c: In function `Perl_pp_flop’: pp_ctl.c:1227: warning: `n’ might be used uninitialized in this function cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic pp_hot.c In file included from perl.h:6161, from pp_hot.c:36: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic pp.c cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic perly.c In file included from perl.h:6161, from pp.c:28: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression In file included from perl.h:6161, from perly.c:26: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic perl.c In file included from perl.h:6161, from perl.c:38: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression In file included from perl.c:3944: intrpvar.h: In function `S_init_interp’: intrpvar.h:813: warning: `Perl_sv_nounlocking’ is deprecated (declared at proto.h:3526) cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic mro_core.c In file included from perl.h:6161, from mro_core.c:31: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic reentr.c cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic mg.c In file included from perl.h:6161, from reentr.c:33: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic hv.c In file included from perl.h:6161, from mg.c:43: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression In file included from perl.h:6161, from hv.c:35: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic gv.c cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic dump.c In file included from perl.h:6161, from gv.c:36: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression In file included from perl.h:6161, from dump.c:29: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression dump.c: In function `Perl_do_sv_dump’: dump.c:2366: warning: long unsigned int format, int arg (arg 4) dump.c:2432: warning: long unsigned int format, int arg (arg 4) dump.c:2462: warning: long unsigned int format, int arg (arg 4) cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic doio.c cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic doop.c In file included from perl.h:6161, from doop.c:24: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression In file included from perl.h:6161, from doio.c:27: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic op.c In file included from perl.h:6161, from op.c:163: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic scope.c In file included from perl.h:6161, from scope.c:27: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic av.c In file included from perl.h:6161, from av.c:24: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression op.c: In function `S_pmtrans’: op.c:7037: warning: `r_cp’ might be used uninitialized in this function op.c:7037: warning: `t_cp’ might be used uninitialized in this function cc -Wl,-E -fstack-protector-strong -o miniperl opmini.o perlmini.o gv.o toke.o perly.o pad.o regcomp.o dump.o util.o mg.o reentr.o mro_core.o keywords.o hv.o av.o run.o pp_hot.o sv.o pp.o scope.o pp_ctl.o pp_sys.o doop.o doio.o regexec.o utf8.o taint.o deb.o universal.o globals.o perlio.o perlapi.o numeric.o mathoms.o locale.o pp_pack.o pp_sort.o caretx.o dquote.o time64.o miniperlmain.o -lm -lc LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -w -Ilib -Idist/Exporter/lib -MExporter -e ‘<?>’ || sh -c ‘echo >&2 Failed to build miniperl. Please run make minitest; exit 1’ LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib -f write_buildcustomize.pl LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib pod/perlmodlib.PL -q LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib autodoc.pl LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib configpm written lib/Config.pod updated install lib/Config_heavy.pl updated lib/Config.pm updated lib/Config_heavy.pl LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/version/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/version directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/podlators/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Generating a Unix-style Makefile Writing Makefile for Pod «../../miniperl» «-I../../lib» «-I../../lib» scripts/pod2text.PL scripts/pod2text «../../miniperl» «-I../../lib» «-I../../lib» scripts/pod2man.PL scripts/pod2man Extracting pod2text (with variable substitutions) cp scripts/pod2text blib/script/pod2text /usr/obj/gnu/usr.bin/perl/cpan/podlators/../../miniperl «-I../../lib» -MExtUtils::MY -e ‘MY->fixin(shift)’ — blib/script/pod2text Extracting pod2man (with variable substitutions) cp scripts/pod2man blib/script/pod2man /usr/obj/gnu/usr.bin/perl/cpan/podlators/../../miniperl «-I../../lib» -MExtUtils::MY -e ‘MY->fixin(shift)’ — blib/script/pod2man Pod::Man is not available: Can’t locate Pod/Simple.pm in @INC (you may need to install the Pod::Simple module) (@INC contains: /usr/obj/gnu/usr.bin/perl/cpan/AutoLoader/lib /usr/obj/gnu/usr.bin/perl/dist/Carp/lib /usr/obj/gnu/usr.bin/perl/dist/PathTools /usr/obj/gnu/usr.bin/perl/dist/PathTools/lib /usr/obj/gnu/usr.bin/perl/cpan/ExtUtils-Install/lib /usr/obj/gnu/usr.bin/perl/cpan/ExtUtils-MakeMaker/lib /usr/obj/gnu/usr.bin/perl/cpan/ExtUtils-Manifest/lib /usr/obj/gnu/usr.bin/perl/cpan/File-Path/lib /usr/obj/gnu/usr.bin/perl/ext/re /usr/obj/gnu/usr.bin/perl/dist/Term-ReadLine/lib /usr/obj/gnu/usr.bin/perl/dist/Exporter/lib /usr/obj/gnu/usr.bin/perl/ext/File-Find/lib /usr/obj/gnu/usr.bin/perl/cpan/Text-Tabs/lib /usr/obj/gnu/usr.bin/perl/dist/constant/lib /usr/obj/gnu/usr.bin/perl/cpan/version/lib /usr/obj/gnu/usr.bin/perl/cpan/Getopt-Long/lib /usr/obj/gnu/usr.bin/perl/cpan/Text-ParseWords/lib /usr/obj/gnu/usr.bin/perl/lib .) at /usr/obj/gnu/usr.bin/perl/lib/Pod/Man.pm line 25. BEGIN failed—compilation aborted at /usr/obj/gnu/usr.bin/perl/lib/Pod/Man.pm line 25. Compilation failed in require at /usr/obj/gnu/usr.bin/perl/cpan/ExtUtils-MakeMaker/lib/ExtUtils/Command/MM.pm line 109. Man pages will not be generated during this install. LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/perlfaq/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/perlfaq directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/parent/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/parent directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/libnet/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Generating a Unix-style Makefile Writing Makefile for Net LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl dist/lib/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Generating a Unix-style Makefile Writing Makefile for lib «../../miniperl» «-I../../lib» lib_pm.PL lib.pm Extracting lib.pm (with variable substitutions) LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl dist/if/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Generating a Unix-style Makefile Writing Makefile for if LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/IO-Compress/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Generating a Unix-style Makefile Writing Makefile for IO::Compress cp bin/zipdetails blib/script/zipdetails /usr/obj/gnu/usr.bin/perl/cpan/IO-Compress/../../miniperl «-I../../lib» -MExtUtils::MY -e ‘MY->fixin(shift)’ — blib/script/zipdetails cp bin/streamzip blib/script/streamzip /usr/obj/gnu/usr.bin/perl/cpan/IO-Compress/../../miniperl «-I../../lib» -MExtUtils::MY -e ‘MY->fixin(shift)’ — blib/script/streamzip LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/Pod-Simple/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/Pod-Simple directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/experimental/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/experimental directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl dist/encoding-warnings/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for dist/encoding-warnings directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl dist/constant/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for dist/constant directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/bignum/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/bignum directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl dist/base/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Generating a Unix-style Makefile Writing Makefile for base LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl dist/autouse/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for dist/autouse directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/autodie/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/autodie directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl dist/XSLoader/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Generating a Unix-style Makefile Writing Makefile for XSLoader «../../miniperl» «-I../../lib» XSLoader_pm.PL XSLoader.pm LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/Time-Local/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/Time-Local directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/Tie-RefHash/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/Tie-RefHash directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl ext/Tie-Memoize/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for ext/Tie-Memoize directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl ext/Tie-Hash-NamedCapture/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for ext/Tie-Hash-NamedCapture directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl dist/Tie-File/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for dist/Tie-File directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl dist/Thread-Semaphore/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for dist/Thread-Semaphore directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl dist/Thread-Queue/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for dist/Thread-Queue directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/Text-Tabs/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/Text-Tabs directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/Text-ParseWords/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/Text-ParseWords directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/Text-Balanced/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/Text-Balanced directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl dist/Text-Abbrev/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for dist/Text-Abbrev directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/Test-Simple/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/Test-Simple directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/Test-Harness/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Generating a Unix-style Makefile Writing Makefile for Test::Harness LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl dist/Test/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for dist/Test directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl dist/Term-ReadLine/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for dist/Term-ReadLine directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl dist/Term-Complete/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for dist/Term-Complete directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/Term-Cap/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Generating a Unix-style Makefile Writing Makefile for Term::Cap LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/Term-ANSIColor/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/Term-ANSIColor directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl dist/Search-Dict/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for dist/Search-Dict directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl dist/Safe/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for dist/Safe directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/Pod-Usage/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Generating a Unix-style Makefile Writing Makefile for Pod::Usage «../../miniperl» «-I../../lib» «-I../../lib» pod2usage.PL pod2usage Extracting pod2usage (with variable substitutions) cp pod2usage blib/script/pod2usage /usr/obj/gnu/usr.bin/perl/cpan/Pod-Usage/../../miniperl «-I../../lib» -MExtUtils::MY -e ‘MY->fixin(shift)’ — blib/script/pod2usage LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/Pod-Perldoc/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Generating a Unix-style Makefile Writing Makefile for Pod::Perldoc LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl ext/Pod-Html/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Generating a Unix-style Makefile Writing Makefile for Pod::Html LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/Pod-Escapes/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/Pod-Escapes directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/Pod-Checker/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Generating a Unix-style Makefile Writing Makefile for Pod::Checker «../../miniperl» «-I../../lib» «-I../../lib» podchecker.PL podchecker Extracting podchecker (with variable substitutions) cp podchecker blib/script/podchecker /usr/obj/gnu/usr.bin/perl/cpan/Pod-Checker/../../miniperl «-I../../lib» -MExtUtils::MY -e ‘MY->fixin(shift)’ — blib/script/podchecker LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl ext/Pod-Functions/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Generating a Unix-style Makefile Writing Makefile for Pod::Functions «../../miniperl» «-I../../lib» Functions_pm.PL ../../pod/perlfunc.pod LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/PerlIO-via-QuotedPrint/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/PerlIO-via-QuotedPrint directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/Perl-OSType/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/Perl-OSType directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/Params-Check/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/Params-Check directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl dist/Net-Ping/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for dist/Net-Ping directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/NEXT/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/NEXT directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/Module-Metadata/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Generating a Unix-style Makefile Writing Makefile for Module::Metadata LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/Module-Loaded/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/Module-Loaded directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/Module-Load-Conditional/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/Module-Load-Conditional directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/Module-Load/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/Module-Load directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl dist/Module-CoreList/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Generating a Unix-style Makefile Writing Makefile for Module::CoreList cp corelist blib/script/corelist /usr/obj/gnu/usr.bin/perl/dist/Module-CoreList/../../miniperl «-I../../lib» -MExtUtils::MY -e ‘MY->fixin(shift)’ — blib/script/corelist LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/Memoize/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/Memoize directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/Math-Complex/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/Math-Complex directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/Math-BigRat/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/Math-BigRat directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/Math-BigInt/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/Math-BigInt directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/Locale-Maketext-Simple/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/Locale-Maketext-Simple directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl dist/Locale-Maketext/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for dist/Locale-Maketext directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/JSON-PP/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Generating a Unix-style Makefile Writing Makefile for JSON::PP LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl ext/IPC-Open3/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for ext/IPC-Open3 directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/IPC-Cmd/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/IPC-Cmd directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/IO-Zlib/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/IO-Zlib directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/IO-Socket-IP/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/IO-Socket-IP directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl dist/I18N-LangTags/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for dist/I18N-LangTags directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl dist/I18N-Collate/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for dist/I18N-Collate directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/HTTP-Tiny/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Generating a Unix-style Makefile Writing Makefile for HTTP::Tiny LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/Getopt-Long/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/Getopt-Long directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl dist/FindBin/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for dist/FindBin directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl dist/Filter-Simple/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for dist/Filter-Simple directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl ext/FileCache/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for ext/FileCache directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/File-Temp/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/File-Temp directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/File-Path/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/File-Path directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl ext/File-Find/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for ext/File-Find directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/File-Fetch/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/File-Fetch directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl dist/ExtUtils-ParseXS/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for dist/ExtUtils-ParseXS directly Generating a Unix-style Makefile Writing Makefile for ExtUtils::ParseXS LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl ext/ExtUtils-Miniperl/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for ext/ExtUtils-Miniperl directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/ExtUtils-Manifest/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/ExtUtils-Manifest directly Generating a Unix-style Makefile Writing Makefile for ExtUtils::Manifest LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib -MExtUtils::Miniperl -e ‘writemain(«perlmain.c», @ARGV)’ DynaLoader LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl dist/SelfLoader/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for dist/SelfLoader directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/ExtUtils-MakeMaker/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 cc -c -DPERL_CORE -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -std=c89 -O2 -Wall -Wextra -Wwrite-strings -DPIC -fpic perlmain.c Generating a Unix-style Makefile Writing Makefile for ExtUtils::MakeMaker LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/ExtUtils-Install/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/ExtUtils-Install directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/ExtUtils-Constant/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/ExtUtils-Constant directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl dist/ExtUtils-CBuilder/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 In file included from perl.h:6161, from perlmain.c:51: inline.h: In function `Perl_utf8n_to_uvchr_msgs’: inline.h:1818: warning: signed and unsigned type in conditional expression Running pm_to_blib for dist/ExtUtils-CBuilder directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl dist/Exporter/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for dist/Exporter directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl dist/Env/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for dist/Env directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl dist/Dumpvalue/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for dist/Dumpvalue directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/Digest/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/Digest directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl dist/Devel-SelfStubber/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for dist/Devel-SelfStubber directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/Config-Perl-V/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/Config-Perl-V directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl dist/Carp/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for dist/Carp directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/CPAN-Meta-YAML/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/CPAN-Meta-YAML directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/CPAN-Meta-Requirements/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/CPAN-Meta-Requirements directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/CPAN-Meta/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Generating a Unix-style Makefile Writing Makefile for CPAN::Meta LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/CPAN/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Generating a Unix-style Makefile Writing Makefile for CPAN LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/AutoLoader/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for cpan/AutoLoader directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl dist/Attribute-Handlers/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Running pm_to_blib for dist/Attribute-Handlers directly LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl cpan/Archive-Tar/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Generating a Unix-style Makefile Writing Makefile for Archive::Tar LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib utils/Makefile.PL LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl ext/Errno/pm_to_blib MAKE=»make» LIBPERL_A=libperl.so.22.0 Extracting utils/Makefile (with variable substitutions) Generating a Unix-style Makefile Writing Makefile for Errno «../../miniperl» «-I../../lib» Errno_pm.PL Errno.pm LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl DynaLoader.o MAKE=»make» LIBPERL_A=libperl.so.22.0 LINKTYPE=static Generating a Unix-style Makefile Writing Makefile for DynaLoader rm -f DynaLoader.xs cp dl_dlopen.xs DynaLoader.xs «../../miniperl» «-I../../lib» «../../lib/ExtUtils/xsubpp» -noprototypes -typemap ‘/usr/obj/gnu/usr.bin/perl/ext/DynaLoader/../../lib/ExtUtils/typemap’ DynaLoader.xs > DynaLoader.xsc «../../miniperl» «-I../../lib» DynaLoader_pm.PL DynaLoader.pm mv DynaLoader.xsc DynaLoader.c cc -c -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -DDLOPEN_WONT_DO_RELATIVE_PATHS -Wall -Wextra -Wwrite-strings -O2 -DVERSION=»1.47_01″ -DXS_VERSION=»1.47_01″ -DPIC -fpic «-I../..» -DLIBC=»/usr/lib/libc.a» DynaLoader.c In file included from ../../perl.h:6161, from DynaLoader.xs:136: ../../inline.h: In function `Perl_utf8n_to_uvchr_msgs’: ../../inline.h:1818: warning: signed and unsigned type in conditional expression rm -rf ../../DynaLoader.o cp DynaLoader.o ../../DynaLoader.o LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib mkppport touch uni.data rm -f libperl.so.22.0 cc -o libperl.so.22.0 -shared -fpic -fstack-protector-strong op.o perl.o gv.o toke.o perly.o pad.o regcomp.o dump.o util.o mg.o reentr.o mro_core.o keywords.o hv.o av.o run.o pp_hot.o sv.o pp.o scope.o pp_ctl.o pp_sys.o doop.o doio.o regexec.o utf8.o taint.o deb.o universal.o globals.o perlio.o perlapi.o numeric.o mathoms.o locale.o pp_pack.o pp_sort.o caretx.o dquote.o time64.o DynaLoader.o -lm -lc cc -o perl -Wl,-E -fstack-protector-strong -Wl,-R/usr/libdata/perl5/m88k-openbsd/CORE perlmain.o -L. -lperl `cat ext.libs` -lm -lc running «/usr/obj/gnu/usr.bin/perl/miniperl» -I../../lib PPPort_pm.PL including ppphdoc including inctools including ppphbin including version including threads including limits including variables including subparse including newCONSTSUB including magic_defs including misc including sv_xpvf including SvPV including warn including format including uv including memory including mess including mPUSH including call including newRV including MY_CXT including SvREFCNT including newSV_type including newSVpv including Sv_set including shared_pv including HvNAME including gv including pvs including magic including cop including grok including snprintf including sprintf including exception including strlfuncs including utf8 including pv_tools including locale running «/usr/obj/gnu/usr.bin/perl/miniperl» -I../../lib ppport_h.PL installing ppport.h for cpan/DB_File installing ppport.h for cpan/IPC-SysV installing ppport.h for cpan/Win32API-File installing ppport.h for dist/IO installing ppport.h for dist/Storable removing temporary file PPPort.pm removing temporary file ppport.h LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl lib/auto/threads/shared/shared.so MAKE=»make» LIBPERL_A=libperl.so.22.0 LINKTYPE=dynamic Generating a Unix-style Makefile Writing Makefile for threads::shared «../../miniperl» «-I../../lib» «../../lib/ExtUtils/xsubpp» -typemap ‘/usr/obj/gnu/usr.bin/perl/dist/threads-shared/../../lib/ExtUtils/typemap’ shared.xs > shared.xsc Running Mkbootstrap for shared () chmod 644 «shared.bs» /usr/obj/gnu/usr.bin/perl/dist/threads-shared/../../miniperl «-I../../lib» -MExtUtils::Command::MM -e ‘cp_nonempty’ — shared.bs ../../lib/auto/threads/shared/shared.bs 644 mv shared.xsc shared.c cc -c -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -Wall -Wextra -Wwrite-strings -O2 -DVERSION=»1.61″ -DXS_VERSION=»1.61″ -DPIC -fpic «-I../..» shared.c In file included from ../../perl.h:6161, from shared.xs:131: ../../inline.h: In function `Perl_utf8n_to_uvchr_msgs’: ../../inline.h:1818: warning: signed and unsigned type in conditional expression rm -f ../../lib/auto/threads/shared/shared.so cc -shared -fpic -fstack-protector-strong shared.o -o ../../lib/auto/threads/shared/shared.so chmod 755 ../../lib/auto/threads/shared/shared.so LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl lib/auto/re/re.so MAKE=»make» LIBPERL_A=libperl.so.22.0 LINKTYPE=dynamic Generating a Unix-style Makefile Writing Makefile for re rm -f re_exec.c rm -f re_comp.c cp ../../regexec.c re_exec.c cp ../../regcomp.c re_comp.c rm -f dquote.c cp ../../dquote.c dquote.c rm -f invlist_inline.h cp ../../invlist_inline.h invlist_inline.h «../../miniperl» «-I../../lib» «../../lib/ExtUtils/xsubpp» -noprototypes -typemap ‘/usr/obj/gnu/usr.bin/perl/ext/re/../../lib/ExtUtils/typemap’ re.xs > re.xsc cc -c -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -Wall -Wextra -Wwrite-strings -O2 -DVERSION=»0.40″ -DXS_VERSION=»0.40″ -DPIC -fpic «-I../..» -DPERL_EXT_RE_BUILD -DPERL_EXT_RE_DEBUG -DPERL_EXT re_comp.c cc -c -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -Wall -Wextra -Wwrite-strings -O2 -DVERSION=»0.40″ -DXS_VERSION=»0.40″ -DPIC -fpic «-I../..» -DPERL_EXT_RE_BUILD -DPERL_EXT_RE_DEBUG -DPERL_EXT re_exec.c mv re.xsc re.c cc -c -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -Wall -Wextra -Wwrite-strings -O2 -DVERSION=»0.40″ -DXS_VERSION=»0.40″ -DPIC -fpic «-I../..» -DPERL_EXT_RE_BUILD -DPERL_EXT_RE_DEBUG -DPERL_EXT re.c In file included from ../../perl.h:6161, from re_comp.c:132: ../../inline.h: In function `Perl_utf8n_to_uvchr_msgs’: ../../inline.h:1818: warning: signed and unsigned type in conditional expression In file included from ../../perl.h:6161, from re_exec.c:75: ../../inline.h: In function `Perl_utf8n_to_uvchr_msgs’: ../../inline.h:1818: warning: signed and unsigned type in conditional expression In file included from ../../perl.h:6161, from re.xs:8: ../../inline.h: In function `Perl_utf8n_to_uvchr_msgs’: ../../inline.h:1818: warning: signed and unsigned type in conditional expression Running Mkbootstrap for re () chmod 644 «re.bs» /usr/obj/gnu/usr.bin/perl/ext/re/../../miniperl «-I../../lib» -MExtUtils::Command::MM -e ‘cp_nonempty’ — re.bs ../../lib/auto/re/re.bs 644 re_exec.c: In function `S_dump_exec_pos’: re_exec.c:4170: warning: unsigned int format, U32 arg (arg 12) re_exec.c: In function `S_regmatch’: re_exec.c:6864: warning: comparison between signed and unsigned re_exec.c:6874: warning: comparison between signed and unsigned re_exec.c:6442: warning: `folder’ might be used uninitialized in this function re_exec.c:6443: warning: `fold_array’ might be used uninitialized in this function re_exec.c: In function `S_regrepeat’: re_exec.c:9757: warning: comparison between signed and unsigned rm -f ../../lib/auto/re/re.so cc -shared -fpic -fstack-protector-strong re_exec.o re_comp.o re.o -o ../../lib/auto/re/re.so chmod 755 ../../lib/auto/re/re.so LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl lib/auto/mro/mro.so MAKE=»make» LIBPERL_A=libperl.so.22.0 LINKTYPE=dynamic Generating a Unix-style Makefile Writing Makefile for mro «../../miniperl» «-I../../lib» «../../lib/ExtUtils/xsubpp» -typemap ‘/usr/obj/gnu/usr.bin/perl/ext/mro/../../lib/ExtUtils/typemap’ mro.xs > mro.xsc Running Mkbootstrap for mro () chmod 644 «mro.bs» mv mro.xsc mro.c cc -c -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -Wall -Wextra -Wwrite-strings -O2 -DVERSION=»1.23″ -DXS_VERSION=»1.23″ -DPIC -fpic «-I../..» mro.c /usr/obj/gnu/usr.bin/perl/ext/mro/../../miniperl «-I../../lib» -MExtUtils::Command::MM -e ‘cp_nonempty’ — mro.bs ../../lib/auto/mro/mro.bs 644 In file included from ../../perl.h:6161, from mro.xs:4: ../../inline.h: In function `Perl_utf8n_to_uvchr_msgs’: ../../inline.h:1818: warning: signed and unsigned type in conditional expression mro.c: In function `XS_mro__nextcan’: mro.xs:515: warning: `fq_subname_len’ might be used uninitialized in this function rm -f ../../lib/auto/mro/mro.so cc -shared -fpic -fstack-protector-strong mro.o -o ../../lib/auto/mro/mro.so chmod 755 ../../lib/auto/mro/mro.so LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl lib/auto/attributes/attributes.so MAKE=»make» LIBPERL_A=libperl.so.22.0 LINKTYPE=dynamic Generating a Unix-style Makefile Writing Makefile for attributes «../../miniperl» «-I../../lib» «../../lib/ExtUtils/xsubpp» -typemap ‘/usr/obj/gnu/usr.bin/perl/ext/attributes/../../lib/ExtUtils/typemap’ attributes.xs > attributes.xsc Running Mkbootstrap for attributes () chmod 644 «attributes.bs» mv attributes.xsc attributes.c cc -c -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -Wall -Wextra -Wwrite-strings -O2 -DVERSION=»0.33″ -DXS_VERSION=»0.33″ -DPIC -fpic «-I../..» attributes.c /usr/obj/gnu/usr.bin/perl/ext/attributes/../../miniperl «-I../../lib» -MExtUtils::Command::MM -e ‘cp_nonempty’ — attributes.bs ../../lib/auto/attributes/attributes.bs 644 In file included from ../../perl.h:6161, from attributes.xs:23: ../../inline.h: In function `Perl_utf8n_to_uvchr_msgs’: ../../inline.h:1818: warning: signed and unsigned type in conditional expression rm -f ../../lib/auto/attributes/attributes.so cc -shared -fpic -fstack-protector-strong attributes.o -o ../../lib/auto/attributes/attributes.so chmod 755 ../../lib/auto/attributes/attributes.so LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl lib/auto/XS/Typemap/Typemap.so MAKE=»make» LIBPERL_A=libperl.so.22.0 LINKTYPE=dynamic Generating a Unix-style Makefile Writing Makefile for XS::Typemap «../../miniperl» «-I../../lib» «../../lib/ExtUtils/xsubpp» -typemap ‘/usr/obj/gnu/usr.bin/perl/ext/XS-Typemap/../../lib/ExtUtils/typemap’ Typemap.xs > Typemap.xsc cc -c -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -Wall -Wextra -Wwrite-strings -O2 -DVERSION=»0.17″ -DXS_VERSION=»0.17″ -DPIC -fpic «-I../..» stdio.c Running Mkbootstrap for Typemap () chmod 644 «Typemap.bs» /usr/obj/gnu/usr.bin/perl/ext/XS-Typemap/../../miniperl «-I../../lib» -MExtUtils::Command::MM -e ‘cp_nonempty’ — Typemap.bs ../../lib/auto/XS/Typemap/Typemap.bs 644 mv Typemap.xsc Typemap.c cc -c -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -Wall -Wextra -Wwrite-strings -O2 -DVERSION=»0.17″ -DXS_VERSION=»0.17″ -DPIC -fpic «-I../..» Typemap.c In file included from ../../perl.h:6161, from Typemap.xs:12: ../../inline.h: In function `Perl_utf8n_to_uvchr_msgs’: ../../inline.h:1818: warning: signed and unsigned type in conditional expression rm -f ../../lib/auto/XS/Typemap/Typemap.so cc -shared -fpic -fstack-protector-strong stdio.o Typemap.o -o ../../lib/auto/XS/Typemap/Typemap.so chmod 755 ../../lib/auto/XS/Typemap/Typemap.so LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl lib/auto/XS/APItest/APItest.so MAKE=»make» LIBPERL_A=libperl.so.22.0 LINKTYPE=dynamic Generating a Unix-style Makefile Writing Makefile for XS::APItest «../../miniperl» «-I../../lib» «../../lib/ExtUtils/xsubpp» -typemap ‘/usr/obj/gnu/usr.bin/perl/ext/XS-APItest/../../lib/ExtUtils/typemap’ -typemap ‘/usr/obj/gnu/usr.bin/perl/ext/XS-APItest/typemap’ XSUB-undef-XS_VERSION.xs > XSUB-undef-XS_VERSION.xsc «../../miniperl» «-I../../lib» «../../lib/ExtUtils/xsubpp» -typemap ‘/usr/obj/gnu/usr.bin/perl/ext/XS-APItest/../../lib/ExtUtils/typemap’ -typemap ‘/usr/obj/gnu/usr.bin/perl/ext/XS-APItest/typemap’ APItest.xs > APItest.xsc «../../miniperl» «-I../../lib» «../../lib/ExtUtils/xsubpp» -typemap ‘/usr/obj/gnu/usr.bin/perl/ext/XS-APItest/../../lib/ExtUtils/typemap’ -typemap ‘/usr/obj/gnu/usr.bin/perl/ext/XS-APItest/typemap’ XSUB-redefined-macros.xs > XSUB-redefined-macros.xsc mv XSUB-undef-XS_VERSION.xsc XSUB-undef-XS_VERSION.c mv XSUB-redefined-macros.xsc XSUB-redefined-macros.c cc -c -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -Wno-deprecated-declarations -Wall -Wextra -Wwrite-strings -O2 -DVERSION=»1.09″ -DXS_VERSION=»1.09″ -DPIC -fpic «-I../..» XSUB-redefined-macros.c cc -c -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -Wno-deprecated-declarations -Wall -Wextra -Wwrite-strings -O2 -DVERSION=»1.09″ -DXS_VERSION=»1.09″ -DPIC -fpic «-I../..» notcore.c In file included from ../../perl.h:6161, from core_or_not.inc:4, from notcore.c:2: ../../inline.h: In function `Perl_utf8n_to_uvchr_msgs’: ../../inline.h:1818: warning: signed and unsigned type in conditional expression In file included from ../../perl.h:6161, from XSUB-redefined-macros.xs:2: ../../inline.h: In function `Perl_utf8n_to_uvchr_msgs’: ../../inline.h:1818: warning: signed and unsigned type in conditional expression cc -c -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -Wno-deprecated-declarations -Wall -Wextra -Wwrite-strings -O2 -DVERSION=»1.09″ -DXS_VERSION=»1.09″ -DPIC -fpic «-I../..» exception.c cc -c -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -Wno-deprecated-declarations -Wall -Wextra -Wwrite-strings -O2 -DVERSION=»1.09″ -DXS_VERSION=»1.09″ -DPIC -fpic «-I../..» core.c In file included from ../../perl.h:6161, from exception.c:2: ../../inline.h: In function `Perl_utf8n_to_uvchr_msgs’: ../../inline.h:1818: warning: signed and unsigned type in conditional expression In file included from ../../perl.h:6161, from core_or_not.inc:4, from core.c:2: ../../inline.h: In function `Perl_utf8n_to_uvchr_msgs’: ../../inline.h:1818: warning: signed and unsigned type in conditional expression cc -c -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -Wno-deprecated-declarations -Wall -Wextra -Wwrite-strings -O2 -DVERSION=»1.09″ -DXS_VERSION=»1.09″ -DPIC -fpic «-I../..» XSUB-undef-XS_VERSION.c Running Mkbootstrap for APItest () Writing APItest.bs chmod 644 «APItest.bs» In file included from ../../perl.h:6161, from XSUB-undef-XS_VERSION.xs:2: ../../inline.h: In function `Perl_utf8n_to_uvchr_msgs’: ../../inline.h:1818: warning: signed and unsigned type in conditional expression /usr/obj/gnu/usr.bin/perl/ext/XS-APItest/../../miniperl «-I../../lib» -MExtUtils::Command::MM -e ‘cp_nonempty’ — APItest.bs ../../lib/auto/XS/APItest/APItest.bs 644 mv APItest.xsc APItest.c cc -c -DNO_LOCALE_NUMERIC -DNO_LOCALE_COLLATE -fno-strict-aliasing -fno-delete-null-pointer-checks -pipe -fstack-protector-strong -Wno-deprecated-declarations -Wall -Wextra -Wwrite-strings -O2 -DVERSION=»1.09″ -DXS_VERSION=»1.09″ -DPIC -fpic «-I../..» APItest.c In file included from ../../perl.h:6161, from APItest.xs:10: ../../inline.h: In function `Perl_utf8n_to_uvchr_msgs’: ../../inline.h:1818: warning: signed and unsigned type in conditional expression APItest.xs: In function `XS_XS__APItest__Magic_test_toLOWER_LC’: APItest.xs:6469: warning: signed and unsigned type in conditional expression APItest.xs: In function `XS_XS__APItest__Magic_test_toFOLD_LC’: APItest.xs:6554: warning: signed and unsigned type in conditional expression APItest.xs: In function `XS_XS__APItest__HvMacro_u8_to_u16_le’: APItest.xs:6895: warning: unused variable `u64′ rm -f ../../lib/auto/XS/APItest/APItest.so cc -shared -fpic -fstack-protector-strong APItest.o XSUB-undef-XS_VERSION.o XSUB-redefined-macros.o core.o exception.o notcore.o -o ../../lib/auto/XS/APItest/APItest.so chmod 755 ../../lib/auto/XS/APItest/APItest.so LD_LIBRARY_PATH=/w1/o/cur/src/gnu/usr.bin/perl/obj ./miniperl -Ilib make_ext.pl lib/auto/Unicode/Normalize/Normalize.so MAKE=»make» LIBPERL_A=libperl.so.22.0 LINKTYPE=dynamic Making header files for XS… Malformed UTF-8 character: xa8 (unexpected continuation byte 0xa8, with no preceding start byte) in pack at ./mkheader line 44. Malformed UTF-8 character (fatal) at ./mkheader line 44. Unsuccessful Makefile.PL(dist/Unicode-Normalize): code=65280 at make_ext.pl line 536. *** Error 2 in /w1/o/cur/src/gnu/usr.bin/perl/obj (makefile:576 ‘lib/auto/Unicode/Normalize/Normalize.so’) *** Error 2 in /w1/o/cur/src/gnu/usr.bin/perl (Makefile.bsd-wrapper1:815 ‘perl.build’) *** Error 2 in /w1/o/cur/src/gnu/usr.bin/perl (Makefile.bsd-wrapper:40 ‘all’) *** Error 2 in /w1/o/cur/src/gnu/usr.bin (<bsd.subdir.mk>:48 ‘all’) *** Error 2 in /w1/o/cur/src/gnu (<bsd.subdir.mk>:48 ‘all’) *** Error 2 in . (<bsd.subdir.mk>:48 ‘all’) *** Error 2 in . (Makefile:97 ‘do-build’) *** Error 2 in /usr/src (Makefile:74 ‘build’) Sat Mar 20 04:18:25 JST 2021
  • NAME
  • SYNOPSIS
  • ABSTRACT
  • DESCRIPTION
  • How to use it
    • Initialize via a configuration file
    • Log Levels
    • Log and die or warn
    • Appenders
    • Additional Appenders via Log::Dispatch
    • Appender Example
    • Logging newlines
    • Configuration files
    • Log Layouts
    • Penalties
  • Categories
    • Turn off a component
    • Return Values
    • Pitfalls with Categories
    • Initialize once and only once
    • Custom Filters
    • Performance
  • Cool Tricks
    • Shortcuts
    • Alternative initialization
    • Using LWP to parse URLs
    • Automatic reloading of changed configuration files
    • Variable Substitution
    • Perl Hooks in the Configuration File
    • Restricting what Opcodes can be in a Perl Hook
    • Changing the Log Level on a Logger
    • Custom Log Levels
    • System-wide log levels
    • Easy Mode
    • Stealth loggers
    • Nested Diagnostic Context (NDC)
    • Mapped Diagnostic Context (MDC)
    • Resurrecting hidden Log4perl Statements
    • Access defined appenders
    • Modify appender thresholds
  • Advanced configuration within Perl
  • How about Log::Dispatch::Config?
  • Using Log::Log4perl with wrapper functions and classes
  • Access to Internals
  • Dirty Tricks
  • EXAMPLE
  • INSTALLATION
  • DEVELOPMENT
  • REFERENCES
  • SEE ALSO
  • AUTHORS
  • LICENSE

NAME

Log::Log4perl — Log4j implementation for Perl

SYNOPSIS

                # Easy mode if you like it simple ...

    use Log::Log4perl qw(:easy);
    Log::Log4perl->easy_init($ERROR);

    DEBUG "This doesn't go anywhere";
    ERROR "This gets logged";

        # ... or standard mode for more features:

    Log::Log4perl::init('/etc/log4perl.conf');
    
    --or--
    
        # Check config every 10 secs
    Log::Log4perl::init_and_watch('/etc/log4perl.conf',10);

    --then--
    
    $logger = Log::Log4perl->get_logger('house.bedrm.desk.topdrwr');
    
    $logger->debug('this is a debug message');
    $logger->info('this is an info message');
    $logger->warn('etc');
    $logger->error('..');
    $logger->fatal('..');
    
    #####/etc/log4perl.conf###############################
    log4perl.logger.house              = WARN,  FileAppndr1
    log4perl.logger.house.bedroom.desk = DEBUG, FileAppndr1
    
    log4perl.appender.FileAppndr1      = Log::Log4perl::Appender::File
    log4perl.appender.FileAppndr1.filename = desk.log 
    log4perl.appender.FileAppndr1.layout   = 
                            Log::Log4perl::Layout::SimpleLayout
    ######################################################

ABSTRACT

Log::Log4perl provides a powerful logging API for your application

DESCRIPTION

Log::Log4perl lets you remote-control and fine-tune the logging behaviour of your system from the outside. It implements the widely popular (Java-based) Log4j logging package in pure Perl.

For a detailed tutorial on Log::Log4perl usage, please read

http://www.perl.com/pub/a/2002/09/11/log4perl.html

Logging beats a debugger if you want to know what’s going on in your code during runtime. However, traditional logging packages are too static and generate a flood of log messages in your log files that won’t help you.

Log::Log4perl is different. It allows you to control the number of logging messages generated at three different levels:

  • At a central location in your system (either in a configuration file or in the startup code) you specify which components (classes, functions) of your system should generate logs.

  • You specify how detailed the logging of these components should be by specifying logging levels.

  • You also specify which so-called appenders you want to feed your log messages to («Print it to the screen and also append it to /tmp/my.log») and which format («Write the date first, then the file name and line number, and then the log message») they should be in.

This is a very powerful and flexible mechanism. You can turn on and off your logs at any time, specify the level of detail and make that dependent on the subsystem that’s currently executed.

Let me give you an example: You might find out that your system has a problem in the MySystem::Helpers::ScanDir component. Turning on detailed debugging logs all over the system would generate a flood of useless log messages and bog your system down beyond recognition. With Log::Log4perl, however, you can tell the system: «Continue to log only severe errors to the log file. Open a second log file, turn on full debug logs in the MySystem::Helpers::ScanDir component and dump all messages originating from there into the new log file». And all this is possible by just changing the parameters in a configuration file, which your system can re-read even while it’s running!

How to use it

The Log::Log4perl package can be initialized in two ways: Either via Perl commands or via a log4j-style configuration file.

Initialize via a configuration file

This is the easiest way to prepare your system for using Log::Log4perl. Use a configuration file like this:

    ############################################################
    # A simple root logger with a Log::Log4perl::Appender::File 
    # file appender in Perl.
    ############################################################
    log4perl.rootLogger=ERROR, LOGFILE
    
    log4perl.appender.LOGFILE=Log::Log4perl::Appender::File
    log4perl.appender.LOGFILE.filename=/var/log/myerrs.log
    log4perl.appender.LOGFILE.mode=append
    
    log4perl.appender.LOGFILE.layout=PatternLayout
    log4perl.appender.LOGFILE.layout.ConversionPattern=[%r] %F %L %c - %m%n

These lines define your standard logger that’s appending severe errors to /var/log/myerrs.log, using the format

    [millisecs] source-filename line-number class - message newline

Assuming that this configuration file is saved as log.conf, you need to read it in the startup section of your code, using the following commands:

  use Log::Log4perl;
  Log::Log4perl->init("log.conf");

After that’s done somewhere in the code, you can retrieve logger objects anywhere in the code. Note that there’s no need to carry any logger references around with your functions and methods. You can get a logger anytime via a singleton mechanism:

    package My::MegaPackage;
    use  Log::Log4perl;

    sub some_method {
        my($param) = @_;

        my $log = Log::Log4perl->get_logger("My::MegaPackage");

        $log->debug("Debug message");
        $log->info("Info message");
        $log->error("Error message");

        ...
    }

With the configuration file above, Log::Log4perl will write «Error message» to the specified log file, but won’t do anything for the debug() and info() calls, because the log level has been set to ERROR for all components in the first line of configuration file shown above.

Why Log::Log4perl->get_logger and not Log::Log4perl->new? We don’t want to create a new object every time. Usually in OO-Programming, you create an object once and use the reference to it to call its methods. However, this requires that you pass around the object to all functions and the last thing we want is pollute each and every function/method we’re using with a handle to the Logger:

    sub function {  # Brrrr!!
        my($logger, $some, $other, $parameters) = @_;
    }

Instead, if a function/method wants a reference to the logger, it just calls the Logger’s static get_logger($category) method to obtain a reference to the one and only possible logger object of a certain category. That’s called a singleton if you’re a Gamma fan.

How does the logger know which messages it is supposed to log and which ones to suppress? Log::Log4perl works with inheritance: The config file above didn’t specify anything about My::MegaPackage. And yet, we’ve defined a logger of the category My::MegaPackage. In this case, Log::Log4perl will walk up the namespace hierarchy (My and then we’re at the root) to figure out if a log level is defined somewhere. In the case above, the log level at the root (root always defines a log level, but not necessarily an appender) defines that the log level is supposed to be ERROR — meaning that DEBUG and INFO messages are suppressed. Note that this ‘inheritance’ is unrelated to Perl’s class inheritance, it is merely related to the logger namespace. By the way, if you’re ever in doubt about what a logger’s category is, use $logger->category() to retrieve it.

Log Levels

There are six predefined log levels: FATAL, ERROR, WARN, INFO, DEBUG, and TRACE (in descending priority). Your configured logging level has to at least match the priority of the logging message.

If your configured logging level is WARN, then messages logged with info(), debug(), and trace() will be suppressed. fatal(), error() and warn() will make their way through, because their priority is higher or equal than the configured setting.

Instead of calling the methods

    $logger->trace("...");  # Log a trace message
    $logger->debug("...");  # Log a debug message
    $logger->info("...");   # Log a info message
    $logger->warn("...");   # Log a warn message
    $logger->error("...");  # Log a error message
    $logger->fatal("...");  # Log a fatal message

you could also call the log() method with the appropriate level using the constants defined in Log::Log4perl::Level:

    use Log::Log4perl::Level;

    $logger->log($TRACE, "...");
    $logger->log($DEBUG, "...");
    $logger->log($INFO, "...");
    $logger->log($WARN, "...");
    $logger->log($ERROR, "...");
    $logger->log($FATAL, "...");

This form is rarely used, but it comes in handy if you want to log at different levels depending on an exit code of a function:

    $logger->log( $exit_level{ $rc }, "...");

As for needing more logging levels than these predefined ones: It’s usually best to steer your logging behaviour via the category mechanism instead.

If you need to find out if the currently configured logging level would allow a logger’s logging statement to go through, use the logger’s is_level() methods:

    $logger->is_trace()    # True if trace messages would go through
    $logger->is_debug()    # True if debug messages would go through
    $logger->is_info()     # True if info messages would go through
    $logger->is_warn()     # True if warn messages would go through
    $logger->is_error()    # True if error messages would go through
    $logger->is_fatal()    # True if fatal messages would go through

Example: $logger->is_warn() returns true if the logger’s current level, as derived from either the logger’s category (or, in absence of that, one of the logger’s parent’s level setting) is $WARN, $ERROR or $FATAL.

Also available are a series of more Java-esque functions which return the same values. These are of the format isLevelEnabled(), so $logger->isDebugEnabled() is synonymous to $logger->is_debug().

These level checking functions will come in handy later, when we want to block unnecessary expensive parameter construction in case the logging level is too low to log the statement anyway, like in:

    if($logger->is_error()) {
        $logger->error("Erroneous array: @super_long_array");
    }

If we had just written

    $logger->error("Erroneous array: @super_long_array");

then Perl would have interpolated @super_long_array into the string via an expensive operation only to figure out shortly after that the string can be ignored entirely because the configured logging level is lower than $ERROR.

The to-be-logged message passed to all of the functions described above can consist of an arbitrary number of arguments, which the logging functions just chain together to a single string. Therefore

    $logger->debug("Hello ", "World", "!");  # and
    $logger->debug("Hello World!");

are identical.

Note that even if one of the methods above returns true, it doesn’t necessarily mean that the message will actually get logged. What is_debug() checks is that the logger used is configured to let a message of the given priority (DEBUG) through. But after this check, Log4perl will eventually apply custom filters and forward the message to one or more appenders. None of this gets checked by is_xxx(), for the simple reason that it’s impossible to know what a custom filter does with a message without having the actual message or what an appender does to a message without actually having it log it.

Log and die or warn

Often, when you croak / carp / warn / die, you want to log those messages. Rather than doing the following:

    $logger->fatal($err) && die($err);

you can use the following:

    $logger->logdie($err);

And if instead of using

    warn($message);
    $logger->warn($message);

to both issue a warning via Perl’s warn() mechanism and make sure you have the same message in the log file as well, use:

    $logger->logwarn($message);

Since there is an ERROR level between WARN and FATAL, there are two additional helper functions in case you’d like to use ERROR for either warn() or die():

    $logger->error_warn();
    $logger->error_die();

Finally, there’s the Carp functions that, in addition to logging, also pass the stringified message to their companions in the Carp package:

    $logger->logcarp();        # warn w/ 1-level stack trace
    $logger->logcluck();       # warn w/ full stack trace
    $logger->logcroak();       # die w/ 1-level stack trace
    $logger->logconfess();     # die w/ full stack trace

Appenders

If you don’t define any appenders, nothing will happen. Appenders will be triggered whenever the configured logging level requires a message to be logged and not suppressed.

Log::Log4perl doesn’t define any appenders by default, not even the root logger has one.

Log::Log4perl already comes with a standard set of appenders:

    Log::Log4perl::Appender::Screen
    Log::Log4perl::Appender::ScreenColoredLevels
    Log::Log4perl::Appender::File
    Log::Log4perl::Appender::Socket
    Log::Log4perl::Appender::DBI
    Log::Log4perl::Appender::Synchronized
    Log::Log4perl::Appender::RRDs

to log to the screen, to files and to databases.

On CPAN, you can find additional appenders like

    Log::Log4perl::Layout::XMLLayout

by Guido Carls <gcarls@cpan.org>. It allows for hooking up Log::Log4perl with the graphical Log Analyzer Chainsaw (see «Can I use Log::Log4perl with log4j’s Chainsaw?» in Log::Log4perl::FAQ).

Additional Appenders via Log::Dispatch

Log::Log4perl also supports Dave Rolskys excellent Log::Dispatch framework which implements a wide variety of different appenders.

Here’s the list of appender modules currently available via Log::Dispatch:

       Log::Dispatch::ApacheLog
       Log::Dispatch::DBI (by Tatsuhiko Miyagawa)
       Log::Dispatch::Email,
       Log::Dispatch::Email::MailSend,
       Log::Dispatch::Email::MailSendmail,
       Log::Dispatch::Email::MIMELite
       Log::Dispatch::File
       Log::Dispatch::FileRotate (by Mark Pfeiffer)
       Log::Dispatch::Handle
       Log::Dispatch::Screen
       Log::Dispatch::Syslog
       Log::Dispatch::Tk (by Dominique Dumont)

Please note that in order to use any of these additional appenders, you have to fetch Log::Dispatch from CPAN and install it. Also the particular appender you’re using might require installing the particular module.

For additional information on appenders, please check the Log::Log4perl::Appender manual page.

Appender Example

Now let’s assume that we want to log info() or higher prioritized messages in the Foo::Bar category to both STDOUT and to a log file, say test.log. In the initialization section of your system, just define two appenders using the readily available Log::Log4perl::Appender::File and Log::Log4perl::Appender::Screen modules:

  use Log::Log4perl;

     # Configuration in a string ...
  my $conf = q(
    log4perl.category.Foo.Bar          = INFO, Logfile, Screen

    log4perl.appender.Logfile          = Log::Log4perl::Appender::File
    log4perl.appender.Logfile.filename = test.log
    log4perl.appender.Logfile.layout   = Log::Log4perl::Layout::PatternLayout
    log4perl.appender.Logfile.layout.ConversionPattern = [%r] %F %L %m%n

    log4perl.appender.Screen         = Log::Log4perl::Appender::Screen
    log4perl.appender.Screen.stderr  = 0
    log4perl.appender.Screen.layout = Log::Log4perl::Layout::SimpleLayout
  );

     # ... passed as a reference to init()
  Log::Log4perl::init( $conf );

Once the initialization shown above has happened once, typically in the startup code of your system, just use the defined logger anywhere in your system:

  ##########################
  # ... in some function ...
  ##########################
  my $log = Log::Log4perl::get_logger("Foo::Bar");

    # Logs both to STDOUT and to the file test.log
  $log->info("Important Info!");

The layout settings specified in the configuration section define the format in which the message is going to be logged by the specified appender. The format shown for the file appender is logging not only the message but also the number of milliseconds since the program has started (%r), the name of the file the call to the logger has happened and the line number there (%F and %L), the message itself (%m) and a OS-specific newline character (%n):

    [187] ./myscript.pl 27 Important Info!

The screen appender above, on the other hand, uses a SimpleLayout, which logs the debug level, a hyphen (-) and the log message:

    INFO - Important Info!

For more detailed info on layout formats, see «Log Layouts».

In the configuration sample above, we chose to define a category logger (Foo::Bar). This will cause only messages originating from this specific category logger to be logged in the defined format and locations.

Logging newlines

There’s some controversy between different logging systems as to when and where newlines are supposed to be added to logged messages.

The Log4perl way is that a logging statement should not contain a newline:

    $logger->info("Some message");
    $logger->info("Another message");

If this is supposed to end up in a log file like

    Some message
    Another message

then an appropriate appender layout like «%m%n» will take care of adding a newline at the end of each message to make sure every message is printed on its own line.

Other logging systems, Log::Dispatch in particular, recommend adding the newline to the log statement. This doesn’t work well, however, if you, say, replace your file appender by a database appender, and all of a sudden those newlines scattered around the code don’t make sense anymore.

Assigning matching layouts to different appenders and leaving newlines out of the code solves this problem. If you inherited code that has logging statements with newlines and want to make it work with Log4perl, read the Log::Log4perl::Layout::PatternLayout documentation on how to accomplish that.

Configuration files

As shown above, you can define Log::Log4perl loggers both from within your Perl code or from configuration files. The latter have the unbeatable advantage that you can modify your system’s logging behaviour without interfering with the code at all. So even if your code is being run by somebody who’s totally oblivious to Perl, they still can adapt the module’s logging behaviour to their needs.

Log::Log4perl has been designed to understand Log4j configuration files — as used by the original Java implementation. Instead of reiterating the format description in [2], let me just list three examples (also derived from [2]), which should also illustrate how it works:

    log4j.rootLogger=DEBUG, A1
    log4j.appender.A1=org.apache.log4j.ConsoleAppender
    log4j.appender.A1.layout=org.apache.log4j.PatternLayout
    log4j.appender.A1.layout.ConversionPattern=%-4r %-5p %c %x - %m%n

This enables messages of priority DEBUG or higher in the root hierarchy and has the system write them to the console. ConsoleAppender is a Java appender, but Log::Log4perl jumps through a significant number of hoops internally to map these to their corresponding Perl classes, Log::Log4perl::Appender::Screen in this case.

Second example:

    log4perl.rootLogger=DEBUG, A1
    log4perl.appender.A1=Log::Log4perl::Appender::Screen
    log4perl.appender.A1.layout=PatternLayout
    log4perl.appender.A1.layout.ConversionPattern=%d %-5p %c - %m%n
    log4perl.logger.com.foo=WARN

This defines two loggers: The root logger and the com.foo logger. The root logger is easily triggered by debug-messages, but the com.foo logger makes sure that messages issued within the Com::Foo component and below are only forwarded to the appender if they’re of priority warning or higher.

Note that the com.foo logger doesn’t define an appender. Therefore, it will just propagate the message up the hierarchy until the root logger picks it up and forwards it to the one and only appender of the root category, using the format defined for it.

Third example:

    log4j.rootLogger=DEBUG, stdout, R
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%5p (%F:%L) - %m%n
    log4j.appender.R=org.apache.log4j.RollingFileAppender
    log4j.appender.R.File=example.log
    log4j.appender.R.layout=org.apache.log4j.PatternLayout
    log4j.appender.R.layout.ConversionPattern=%p %c - %m%n

The root logger defines two appenders here: stdout, which uses org.apache.log4j.ConsoleAppender (ultimately mapped by Log::Log4perl to Log::Log4perl::Appender::Screen) to write to the screen. And R, a org.apache.log4j.RollingFileAppender (mapped by Log::Log4perl to Log::Dispatch::FileRotate with the File attribute specifying the log file.

See Log::Log4perl::Config for more examples and syntax explanations.

Log Layouts

If the logging engine passes a message to an appender, because it thinks it should be logged, the appender doesn’t just write it out haphazardly. There’s ways to tell the appender how to format the message and add all sorts of interesting data to it: The date and time when the event happened, the file, the line number, the debug level of the logger and others.

There’s currently two layouts defined in Log::Log4perl: Log::Log4perl::Layout::SimpleLayout and Log::Log4perl::Layout::PatternLayout:

Log::Log4perl::SimpleLayout

formats a message in a simple way and just prepends it by the debug level and a hyphen: "$level - $message, for example "FATAL - Can't open password file".

Log::Log4perl::Layout::PatternLayout

on the other hand is very powerful and allows for a very flexible format in printf-style. The format string can contain a number of placeholders which will be replaced by the logging engine when it’s time to log the message:

    %c Category of the logging event.
    %C Fully qualified package (or class) name of the caller
    %d Current date in yyyy/MM/dd hh:mm:ss format
    %F File where the logging event occurred
    %H Hostname (if Sys::Hostname is available)
    %l Fully qualified name of the calling method followed by the
       callers source the file name and line number between 
       parentheses.
    %L Line number within the file where the log statement was issued
    %m The message to be logged
    %m{chomp} The message to be logged, stripped off a trailing newline
    %M Method or function where the logging request was issued
    %n Newline (OS-independent)
    %p Priority of the logging event
    %P pid of the current process
    %r Number of milliseconds elapsed from program start to logging 
       event
    %R Number of milliseconds elapsed from last logging event to
       current logging event 
    %T A stack trace of functions called
    %x The topmost NDC (see below)
    %X{key} The entry 'key' of the MDC (see below)
    %% A literal percent (%) sign

NDC and MDC are explained in «Nested Diagnostic Context (NDC)» and «Mapped Diagnostic Context (MDC)».

Also, %d can be fine-tuned to display only certain characteristics of a date, according to the SimpleDateFormat in the Java World (http://java.sun.com/j2se/1.3/docs/api/java/text/SimpleDateFormat.html)

In this way, %d{HH:mm} displays only hours and minutes of the current date, while %d{yy, EEEE} displays a two-digit year, followed by a spelled-out day (like Wednesday).

Similar options are available for shrinking the displayed category or limit file/path components, %F{1} only displays the source file name without any path components while %F logs the full path. %c{2} only logs the last two components of the current category, Foo::Bar::Baz becomes Bar::Baz and saves space.

If those placeholders aren’t enough, then you can define your own right in the config file like this:

    log4perl.PatternLayout.cspec.U = sub { return "UID $<" }

See Log::Log4perl::Layout::PatternLayout for further details on customized specifiers.

Please note that the subroutines you’re defining in this way are going to be run in the main namespace, so be sure to fully qualify functions and variables if they’re located in different packages.

SECURITY NOTE: this feature means arbitrary perl code can be embedded in the config file. In the rare case where the people who have access to your config file are different from the people who write your code and shouldn’t have execute rights, you might want to call

    Log::Log4perl::Config->allow_code(0);

before you call init(). Alternatively you can supply a restricted set of Perl opcodes that can be embedded in the config file as described in «Restricting what Opcodes can be in a Perl Hook».

All placeholders are quantifiable, just like in printf. Following this tradition, %-20c will reserve 20 chars for the category and left-justify it.

For more details on logging and how to use the flexible and the simple format, check out the original log4j website under

SimpleLayout and PatternLayout

Penalties

Logging comes with a price tag. Log::Log4perl has been optimized to allow for maximum performance, both with logging enabled and disabled.

But you need to be aware that there’s a small hit every time your code encounters a log statement — no matter if logging is enabled or not. Log::Log4perl has been designed to keep this so low that it will be unnoticeable to most applications.

Here’s a couple of tricks which help Log::Log4perl to avoid unnecessary delays:

You can save serious time if you’re logging something like

        # Expensive in non-debug mode!
    for (@super_long_array) {
        $logger->debug("Element: $_");
    }

and @super_long_array is fairly big, so looping through it is pretty expensive. Only you, the programmer, knows that going through that for loop can be skipped entirely if the current logging level for the actual component is higher than debug. In this case, use this instead:

        # Cheap in non-debug mode!
    if($logger->is_debug()) {
        for (@super_long_array) {
            $logger->debug("Element: $_");
        }
    }

If you’re afraid that generating the parameters to the logging function is fairly expensive, use closures:

        # Passed as subroutine ref
    use Data::Dumper;
    $logger->debug(sub { Dumper($data) } );

This won’t unravel $data via Dumper() unless it’s actually needed because it’s logged.

Also, Log::Log4perl lets you specify arguments to logger functions in message output filter syntax:

    $logger->debug("Structure: ",
                   { filter => &Dumper,
                     value  => $someref });

In this way, shortly before Log::Log4perl sending the message out to any appenders, it will be searching all arguments for hash references and treat them in a special way:

It will invoke the function given as a reference with the filter key (Data::Dumper::Dumper()) and pass it the value that came with the key named value as an argument. The anonymous hash in the call above will be replaced by the return value of the filter function.

Categories

Categories are also called «Loggers» in Log4perl, both refer to the same thing and these terms are used interchangeably. Log::Log4perl uses categories to determine if a log statement in a component should be executed or suppressed at the current logging level. Most of the time, these categories are just the classes the log statements are located in:

    package Candy::Twix;

    sub new { 
        my $logger = Log::Log4perl->get_logger("Candy::Twix");
        $logger->debug("Creating a new Twix bar");
        bless {}, shift;
    }
 
    # ...

    package Candy::Snickers;

    sub new { 
        my $logger = Log::Log4perl->get_logger("Candy.Snickers");
        $logger->debug("Creating a new Snickers bar");
        bless {}, shift;
    }

    # ...

    package main;
    Log::Log4perl->init("mylogdefs.conf");

        # => "LOG> Creating a new Snickers bar"
    my $first = Candy::Snickers->new();
        # => "LOG> Creating a new Twix bar"
    my $second = Candy::Twix->new();

Note that you can separate your category hierarchy levels using either dots like in Java (.) or double-colons (::) like in Perl. Both notations are equivalent and are handled the same way internally.

However, categories are just there to make use of inheritance: if you invoke a logger in a sub-category, it will bubble up the hierarchy and call the appropriate appenders. Internally, categories are not related to the class hierarchy of the program at all — they’re purely virtual. You can use arbitrary categories — for example in the following program, which isn’t oo-style, but procedural:

    sub print_portfolio {

        my $log = Log::Log4perl->get_logger("user.portfolio");
        $log->debug("Quotes requested: @_");

        for(@_) {
            print "$_: ", get_quote($_), "n";
        }
    }

    sub get_quote {

        my $log = Log::Log4perl->get_logger("internet.quotesystem");
        $log->debug("Fetching quote: $_[0]");

        return yahoo_quote($_[0]);
    }

The logger in first function, print_portfolio, is assigned the (virtual) user.portfolio category. Depending on the Log4perl configuration, this will either call a user.portfolio appender, a user appender, or an appender assigned to root — without user.portfolio having any relevance to the class system used in the program. The logger in the second function adheres to the internet.quotesystem category — again, maybe because it’s bundled with other Internet functions, but not because there would be a class of this name somewhere.

However, be careful, don’t go overboard: if you’re developing a system in object-oriented style, using the class hierarchy is usually your best choice. Think about the people taking over your code one day: The class hierarchy is probably what they know right up front, so it’s easy for them to tune the logging to their needs.

Turn off a component

Log4perl doesn’t only allow you to selectively switch on a category of log messages, you can also use the mechanism to selectively disable logging in certain components whereas logging is kept turned on in higher-level categories. This mechanism comes in handy if you find that while bumping up the logging level of a high-level (i. e. close to root) category, that one component logs more than it should,

Here’s how it works:

    ############################################################
    # Turn off logging in a lower-level category while keeping
    # it active in higher-level categories.
    ############################################################
    log4perl.rootLogger=DEBUG, LOGFILE
    log4perl.logger.deep.down.the.hierarchy = ERROR, LOGFILE

    # ... Define appenders ...

This way, log messages issued from within Deep::Down::The::Hierarchy and below will be logged only if they’re ERROR or worse, while in all other system components even DEBUG messages will be logged.

Return Values

All logging methods return values indicating if their message actually reached one or more appenders. If the message has been suppressed because of level constraints, undef is returned.

For example,

    my $ret = $logger->info("Message");

will return undef if the system debug level for the current category is not INFO or more permissive. If Log::Log4perl forwarded the message to one or more appenders, the number of appenders is returned.

If appenders decide to veto on the message with an appender threshold, the log method’s return value will have them excluded. This means that if you’ve got one appender holding an appender threshold and you’re logging a message which passes the system’s log level hurdle but not the appender threshold, 0 will be returned by the log function.

The bottom line is: Logging functions will return a true value if the message made it through to one or more appenders and a false value if it didn’t. This allows for constructs like

    $logger->fatal("@_") or print STDERR "@_n";

which will ensure that the fatal message isn’t lost if the current level is lower than FATAL or printed twice if the level is acceptable but an appender already points to STDERR.

Pitfalls with Categories

Be careful with just blindly reusing the system’s packages as categories. If you do, you’ll get into trouble with inherited methods. Imagine the following class setup:

    use Log::Log4perl;

    ###########################################
    package Bar;
    ###########################################
    sub new {
        my($class) = @_;
        my $logger = Log::Log4perl::get_logger(__PACKAGE__);
        $logger->debug("Creating instance");
        bless {}, $class;
    }
    ###########################################
    package Bar::Twix;
    ###########################################
    our @ISA = qw(Bar);

    ###########################################
    package main;
    ###########################################
    Log::Log4perl->init( qq{
    log4perl.category.Bar.Twix = DEBUG, Screen
    log4perl.appender.Screen = Log::Log4perl::Appender::Screen
    log4perl.appender.Screen.layout = SimpleLayout
    });

    my $bar = Bar::Twix->new();

Bar::Twix just inherits everything from Bar, including the constructor new(). Contrary to what you might be thinking at first, this won’t log anything. Reason for this is the get_logger() call in package Bar, which will always get a logger of the Bar category, even if we call new() via the Bar::Twix package, which will make perl go up the inheritance tree to actually execute Bar::new(). Since we’ve only defined logging behaviour for Bar::Twix in the configuration file, nothing will happen.

This can be fixed by changing the get_logger() method in Bar::new() to obtain a logger of the category matching the actual class of the object, like in

        # ... in Bar::new() ...
    my $logger = Log::Log4perl::get_logger( $class );

In a method other than the constructor, the class name of the actual object can be obtained by calling ref() on the object reference, so

    package BaseClass;
    use Log::Log4perl qw( get_logger );

    sub new { 
        bless {}, shift; 
    }

    sub method {
        my( $self ) = @_;

        get_logger( ref $self )->debug( "message" );
    }

    package SubClass;
    our @ISA = qw(BaseClass);

is the recommended pattern to make sure that

    my $sub = SubClass->new();
    $sub->meth();

starts logging if the "SubClass" category (and not the "BaseClass" category has logging enabled at the DEBUG level.

Initialize once and only once

It’s important to realize that Log::Log4perl gets initialized once and only once, typically at the start of a program or system. Calling init() more than once will cause it to clobber the existing configuration and replace it by the new one.

If you’re in a traditional CGI environment, where every request is handled by a new process, calling init() every time is fine. In persistent environments like mod_perl, however, Log::Log4perl should be initialized either at system startup time (Apache offers startup handlers for that) or via

        # Init or skip if already done
    Log::Log4perl->init_once($conf_file);

init_once() is identical to init(), just with the exception that it will leave a potentially existing configuration alone and will only call init() if Log::Log4perl hasn’t been initialized yet.

If you’re just curious if Log::Log4perl has been initialized yet, the check

    if(Log::Log4perl->initialized()) {
        # Yes, Log::Log4perl has already been initialized
    } else {
        # No, not initialized yet ...
    }

can be used.

If you’re afraid that the components of your system are stepping on each other’s toes or if you are thinking that different components should initialize Log::Log4perl separately, try to consolidate your system to use a centralized Log4perl configuration file and use Log4perl’s categories to separate your components.

Custom Filters

Log4perl allows the use of customized filters in its appenders to control the output of messages. These filters might grep for certain text chunks in a message, verify that its priority matches or exceeds a certain level or that this is the 10th time the same message has been submitted — and come to a log/no log decision based upon these circumstantial facts.

Check out Log::Log4perl::Filter for detailed instructions on how to use them.

Performance

The performance of Log::Log4perl calls obviously depends on a lot of things. But to give you a general idea, here’s some rough numbers:

On a Pentium 4 Linux box at 2.4 GHz, you’ll get through

  • 500,000 suppressed log statements per second

  • 30,000 logged messages per second (using an in-memory appender)

  • init_and_watch delay mode: 300,000 suppressed, 30,000 logged. init_and_watch signal mode: 450,000 suppressed, 30,000 logged.

Numbers depend on the complexity of the Log::Log4perl configuration. For a more detailed benchmark test, check the docs/benchmark.results.txt document in the Log::Log4perl distribution.

Cool Tricks

Here’s a collection of useful tricks for the advanced Log::Log4perl user. For more, check the FAQ, either in the distribution (Log::Log4perl::FAQ) or on http://log4perl.sourceforge.net.

Shortcuts

When getting an instance of a logger, instead of saying

    use Log::Log4perl;
    my $logger = Log::Log4perl->get_logger();

it’s often more convenient to import the get_logger method from Log::Log4perl into the current namespace:

    use Log::Log4perl qw(get_logger);
    my $logger = get_logger();

Please note this difference: To obtain the root logger, please use get_logger(""), call it without parameters (get_logger()), you’ll get the logger of a category named after the current package. get_logger() is equivalent to get_logger(__PACKAGE__).

Alternative initialization

Instead of having init() read in a configuration file by specifying a file name or passing it a reference to an open filehandle (Log::Log4perl->init( *FILE )), you can also pass in a reference to a string, containing the content of the file:

    Log::Log4perl->init( $config_text );

Also, if you’ve got the name=value pairs of the configuration in a hash, you can just as well initialize Log::Log4perl with a reference to it:

    my %key_value_pairs = (
        "log4perl.rootLogger"       => "ERROR, LOGFILE",
        "log4perl.appender.LOGFILE" => "Log::Log4perl::Appender::File",
        ...
    );

    Log::Log4perl->init( %key_value_pairs );

Or also you can use a URL, see below:

Using LWP to parse URLs

(This section borrowed from XML::DOM::Parser by T.J. Mather).

The init() function now also supports URLs, e.g. http://www.erols.com/enno/xsa.xml. It uses LWP to download the file and then calls parse() on the resulting string. By default it will use a LWP::UserAgent that is created as follows:

 use LWP::UserAgent;
 $LWP_USER_AGENT = LWP::UserAgent->new;
 $LWP_USER_AGENT->env_proxy;

Note that env_proxy reads proxy settings from environment variables, which is what Log4perl needs to do to get through our firewall. If you want to use a different LWP::UserAgent, you can set it with

    Log::Log4perl::Config::set_LWP_UserAgent($my_agent);

Currently, LWP is used when the filename (passed to parsefile) starts with one of the following URL schemes: http, https, ftp, wais, gopher, or file (followed by a colon.)

Don’t use this feature with init_and_watch().

Automatic reloading of changed configuration files

Instead of just statically initializing Log::Log4perl via

    Log::Log4perl->init($conf_file);

there’s a way to have Log::Log4perl periodically check for changes in the configuration and reload it if necessary:

    Log::Log4perl->init_and_watch($conf_file, $delay);

In this mode, Log::Log4perl will examine the configuration file $conf_file every $delay seconds for changes via the file’s last modification timestamp. If the file has been updated, it will be reloaded and replace the current Log::Log4perl configuration.

The way this works is that with every logger function called (debug(), is_debug(), etc.), Log::Log4perl will check if the delay interval has expired. If so, it will run a -M file check on the configuration file. If its timestamp has been modified, the current configuration will be dumped and new content of the file will be loaded.

This convenience comes at a price, though: Calling time() with every logging function call, especially the ones that are «suppressed» (!), will slow down these Log4perl calls by about 40%.

To alleviate this performance hit a bit, init_and_watch() can be configured to listen for a Unix signal to reload the configuration instead:

    Log::Log4perl->init_and_watch($conf_file, 'HUP');

This will set up a signal handler for SIGHUP and reload the configuration if the application receives this signal, e.g. via the kill command:

    kill -HUP pid

where pid is the process ID of the application. This will bring you back to about 85% of Log::Log4perl’s normal execution speed for suppressed statements. For details, check out «Performance». For more info on the signal handler, look for «SIGNAL MODE» in Log::Log4perl::Config::Watch.

If you have a somewhat long delay set between physical config file checks or don’t want to use the signal associated with the config file watcher, you can trigger a configuration reload at the next possible time by calling Log::Log4perl::Config->watcher->force_next_check().

One thing to watch out for: If the configuration file contains a syntax or other fatal error, a running application will stop with die if this damaged configuration will be loaded during runtime, triggered either by a signal or if the delay period expired and the change is detected. This behaviour might change in the future.

To allow the application to intercept and control a configuration reload in init_and_watch mode, a callback can be specified:

    Log::Log4perl->init_and_watch($conf_file, 10, { 
            preinit_callback => &callback });

If Log4perl determines that the configuration needs to be reloaded, it will call the preinit_callback function without parameters. If the callback returns a true value, Log4perl will proceed and reload the configuration. If the callback returns a false value, Log4perl will keep the old configuration and skip reloading it until the next time around. Inside the callback, an application can run all kinds of checks, including accessing the configuration file, which is available via Log::Log4perl::Config->watcher()->file().

Variable Substitution

To avoid having to retype the same expressions over and over again, Log::Log4perl’s configuration files support simple variable substitution. New variables are defined simply by adding

    varname = value

lines to the configuration file before using

    ${varname}

afterwards to recall the assigned values. Here’s an example:

    layout_class   = Log::Log4perl::Layout::PatternLayout
    layout_pattern = %d %F{1} %L> %m %n
    
    log4perl.category.Bar.Twix = WARN, Logfile, Screen

    log4perl.appender.Logfile  = Log::Log4perl::Appender::File
    log4perl.appender.Logfile.filename = test.log
    log4perl.appender.Logfile.layout = ${layout_class}
    log4perl.appender.Logfile.layout.ConversionPattern = ${layout_pattern}

    log4perl.appender.Screen  = Log::Log4perl::Appender::Screen
    log4perl.appender.Screen.layout = ${layout_class}
    log4perl.appender.Screen.layout.ConversionPattern = ${layout_pattern}

This is a convenient way to define two appenders with the same layout without having to retype the pattern definitions.

Variable substitution via ${varname} will first try to find an explicitly defined variable. If that fails, it will check your shell’s environment for a variable of that name. If that also fails, the program will die().

Perl Hooks in the Configuration File

If some of the values used in the Log4perl configuration file need to be dynamically modified by the program, use Perl hooks:

    log4perl.appender.File.filename = 
        sub { return getLogfileName(); }

Each value starting with the string sub {... is interpreted as Perl code to be executed at the time the application parses the configuration via Log::Log4perl::init(). The return value of the subroutine is used by Log::Log4perl as the configuration value.

The Perl code is executed in the main package, functions in other packages have to be called in fully-qualified notation.

Here’s another example, utilizing an environment variable as a username for a DBI appender:

    log4perl.appender.DB.username = 
        sub { $ENV{DB_USER_NAME } }

However, please note the difference between these code snippets and those used for user-defined conversion specifiers as discussed in Log::Log4perl::Layout::PatternLayout: While the snippets above are run once when Log::Log4perl::init() is called, the conversion specifier snippets are executed each time a message is rendered according to the PatternLayout.

SECURITY NOTE: this feature means arbitrary perl code can be embedded in the config file. In the rare case where the people who have access to your config file are different from the people who write your code and shouldn’t have execute rights, you might want to set

    Log::Log4perl::Config->allow_code(0);

before you call init(). Alternatively you can supply a restricted set of Perl opcodes that can be embedded in the config file as described in «Restricting what Opcodes can be in a Perl Hook».

Restricting what Opcodes can be in a Perl Hook

The value you pass to Log::Log4perl::Config->allow_code() determines whether the code that is embedded in the config file is eval’d unrestricted, or eval’d in a Safe compartment. By default, a value of ‘1’ is assumed, which does a normal ‘eval’ without any restrictions. A value of ‘0’ however prevents any embedded code from being evaluated.

If you would like fine-grained control over what can and cannot be included in embedded code, then please utilize the following methods:

 Log::Log4perl::Config->allow_code( $allow );
 Log::Log4perl::Config->allowed_code_ops($op1, $op2, ... );
 Log::Log4perl::Config->vars_shared_with_safe_compartment( [ %vars | $package, @vars ] );
 Log::Log4perl::Config->allowed_code_ops_convenience_map( [ %map | $name, @mask ] );

Log::Log4perl::Config->allowed_code_ops() takes a list of opcode masks that are allowed to run in the compartment. The opcode masks must be specified as described in Opcode:

 Log::Log4perl::Config->allowed_code_ops(':subprocess');

This example would allow Perl operations like backticks, system, fork, and waitpid to be executed in the compartment. Of course, you probably don’t want to use this mask — it would allow exactly what the Safe compartment is designed to prevent.

Log::Log4perl::Config->vars_shared_with_safe_compartment() takes the symbols which should be exported into the Safe compartment before the code is evaluated. The keys of this hash are the package names that the symbols are in, and the values are array references to the literal symbol names. For convenience, the default settings export the ‘%ENV’ hash from the ‘main’ package into the compartment:

 Log::Log4perl::Config->vars_shared_with_safe_compartment(
   main => [ '%ENV' ],
 );

Log::Log4perl::Config->allowed_code_ops_convenience_map() is an accessor method to a map of convenience names to opcode masks. At present, the following convenience names are defined:

 safe        = [ ':browse' ]
 restrictive = [ ':default' ]

For convenience, if Log::Log4perl::Config->allow_code() is called with a value which is a key of the map previously defined with Log::Log4perl::Config->allowed_code_ops_convenience_map(), then the allowed opcodes are set according to the value defined in the map. If this is confusing, consider the following:

 use Log::Log4perl;
 
 my $config = <<'END';
  log4perl.logger = INFO, Main
  log4perl.appender.Main = Log::Log4perl::Appender::File
  log4perl.appender.Main.filename = 
      sub { "example" . getpwuid($<) . ".log" }
  log4perl.appender.Main.layout = Log::Log4perl::Layout::SimpleLayout
 END
 
 $Log::Log4perl::Config->allow_code('restrictive');
 Log::Log4perl->init( $config );       # will fail
 $Log::Log4perl::Config->allow_code('safe');
 Log::Log4perl->init( $config );       # will succeed

The reason that the first call to ->init() fails is because the ‘restrictive’ name maps to an opcode mask of ‘:default’. getpwuid() is not part of ‘:default’, so ->init() fails. The ‘safe’ name maps to an opcode mask of ‘:browse’, which allows getpwuid() to run, so ->init() succeeds.

allowed_code_ops_convenience_map() can be invoked in several ways:

allowed_code_ops_convenience_map()

Returns the entire convenience name map as a hash reference in scalar context or a hash in list context.

allowed_code_ops_convenience_map( %map )

Replaces the entire convenience name map with the supplied hash reference.

allowed_code_ops_convenience_map( $name )

Returns the opcode mask for the given convenience name, or undef if no such name is defined in the map.

allowed_code_ops_convenience_map( $name, @mask )

Adds the given name/mask pair to the convenience name map. If the name already exists in the map, it’s value is replaced with the new mask.

as can vars_shared_with_safe_compartment():

vars_shared_with_safe_compartment()

Return the entire map of packages to variables as a hash reference in scalar context or a hash in list context.

vars_shared_with_safe_compartment( %packages )

Replaces the entire map of packages to variables with the supplied hash reference.

vars_shared_with_safe_compartment( $package )

Returns the arrayref of variables to be shared for a specific package.

vars_shared_with_safe_compartment( $package, @vars )

Adds the given package / varlist pair to the map. If the package already exists in the map, it’s value is replaced with the new arrayref of variable names.

For more information on opcodes and Safe Compartments, see Opcode and Safe.

Changing the Log Level on a Logger

Log4perl provides some internal functions for quickly adjusting the log level from within a running Perl program.

Now, some people might argue that you should adjust your levels from within an external Log4perl configuration file, but Log4perl is everybody’s darling.

Typically run-time adjusting of levels is done at the beginning, or in response to some external input (like a «more logging» runtime command for diagnostics).

You get the log level from a logger object with:

    $current_level = $logger->level();

and you may set it with the same method, provided you first imported the log level constants, with:

    use Log::Log4perl::Level;

Then you can set the level on a logger to one of the constants,

    $logger->level($ERROR); # one of DEBUG, INFO, WARN, ERROR, FATAL

To increase the level of logging currently being done, use:

    $logger->more_logging($delta);

and to decrease it, use:

    $logger->less_logging($delta);

$delta must be a positive integer (for now, we may fix this later ;).

There are also two equivalent functions:

    $logger->inc_level($delta);
    $logger->dec_level($delta);

They’re included to allow you a choice in readability. Some folks will prefer more/less_logging, as they’re fairly clear in what they do, and allow the programmer not to worry too much about what a Level is and whether a higher level means more or less logging. However, other folks who do understand and have lots of code that deals with levels will probably prefer the inc_level() and dec_level() methods as they want to work with Levels and not worry about whether that means more or less logging. :)

That diatribe aside, typically you’ll use more_logging() or inc_level() as such:

    my $v = 0; # default level of verbosity.
    
    GetOptions("v+" => $v, ...);

    if( $v ) {
      $logger->more_logging($v); # inc logging level once for each -v in ARGV
    }

Custom Log Levels

First off, let me tell you that creating custom levels is heavily deprecated by the log4j folks. Indeed, instead of creating additional levels on top of the predefined DEBUG, INFO, WARN, ERROR and FATAL, you should use categories to control the amount of logging smartly, based on the location of the log-active code in the system.

Nevertheless, Log4perl provides a nice way to create custom levels via the create_custom_level() routine function. However, this must be done before the first call to init() or get_logger(). Say you want to create a NOTIFY logging level that comes after WARN (and thus before INFO). You’d do such as follows:

    use Log::Log4perl;
    use Log::Log4perl::Level;

    Log::Log4perl::Logger::create_custom_level("NOTIFY", "WARN");

And that’s it! create_custom_level() creates the following functions / variables for level FOO:

    $FOO_INT        # integer to use in L4p::Level::to_level()
    $logger->foo()  # log function to log if level = FOO
    $logger->is_foo()   # true if current level is >= FOO

These levels can also be used in your config file, but note that your config file probably won’t be portable to another log4perl or log4j environment unless you’ve made the appropriate mods there too.

Since Log4perl translates log levels to syslog and Log::Dispatch if their appenders are used, you may add mappings for custom levels as well:

  Log::Log4perl::Level::add_priority("NOTIFY", "WARN",
                                     $syslog_equiv, $log_dispatch_level);

For example, if your new custom «NOTIFY» level is supposed to map to syslog level 2 («LOG_NOTICE») and Log::Dispatch level 2 («notice»), use:

  Log::Log4perl::Logger::create_custom_level("NOTIFY", "WARN", 2, 2);

System-wide log levels

As a fairly drastic measure to decrease (or increase) the logging level all over the system with one single configuration option, use the threshold keyword in the Log4perl configuration file:

    log4perl.threshold = ERROR

sets the system-wide (or hierarchy-wide according to the log4j documentation) to ERROR and therefore deprives every logger in the system of the right to log lower-prio messages.

Easy Mode

For teaching purposes (especially for [1]), I’ve put :easy mode into Log::Log4perl, which just initializes a single root logger with a defined priority and a screen appender including some nice standard layout:

    ### Initialization Section
    use Log::Log4perl qw(:easy);
    Log::Log4perl->easy_init($ERROR);  # Set priority of root logger to ERROR

    ### Application Section
    my $logger = get_logger();
    $logger->fatal("This will get logged.");
    $logger->debug("This won't.");

This will dump something like

    2002/08/04 11:43:09 ERROR> script.pl:16 main::function - This will get logged.

to the screen. While this has been proven to work well familiarizing people with Log::Logperl slowly, effectively avoiding to clobber them over the head with a plethora of different knobs to fiddle with (categories, appenders, levels, layout), the overall mission of Log::Log4perl is to let people use categories right from the start to get used to the concept. So, let’s keep this one fairly hidden in the man page (congrats on reading this far :).

Stealth loggers

Sometimes, people are lazy. If you’re whipping up a 50-line script and want the comfort of Log::Log4perl without having the burden of carrying a separate log4perl.conf file or a 5-liner defining that you want to append your log statements to a file, you can use the following features:

    use Log::Log4perl qw(:easy);

    Log::Log4perl->easy_init( { level   => $DEBUG,
                                file    => ">>test.log" } );

        # Logs to test.log via stealth logger
    DEBUG("Debug this!");
    INFO("Info this!");
    WARN("Warn this!");
    ERROR("Error this!");

    some_function();

    sub some_function {
            # Same here
        FATAL("Fatal this!");
    }

In :easy mode, Log::Log4perl will instantiate a stealth logger and introduce the convenience functions TRACE, DEBUG(), INFO(), WARN(), ERROR(), FATAL(), and ALWAYS into the package namespace. These functions simply take messages as arguments and forward them to the stealth loggers methods (debug(), info(), and so on).

If a message should never be blocked, regardless of the log level, use the ALWAYS function which corresponds to a log level of OFF:

    ALWAYS "This will be printed regardless of the log level";

The easy_init method can be called with a single level value to create a STDERR appender and a root logger as in

    Log::Log4perl->easy_init($DEBUG);

or, as shown below (and in the example above) with a reference to a hash, specifying values for level (the logger’s priority), file (the appender’s data sink), category (the logger’s category and layout for the appender’s pattern layout specification. All key-value pairs are optional, they default to $DEBUG for level, STDERR for file, "" (root category) for category and %d %m%n for layout:

    Log::Log4perl->easy_init( { level    => $DEBUG,
                                file     => ">test.log",
                                utf8     => 1,
                                category => "Bar::Twix",
                                layout   => '%F{1}-%L-%M: %m%n' } );

The file parameter takes file names preceded by ">" (overwrite) and ">>" (append) as arguments. This will cause Log::Log4perl::Appender::File appenders to be created behind the scenes. Also the keywords STDOUT and STDERR (no > or >>) are recognized, which will utilize and configure Log::Log4perl::Appender::Screen appropriately. The utf8 flag, if set to a true value, runs a binmode command on the file handle to establish a utf8 line discipline on the file, otherwise you’ll get a ‘wide character in print’ warning message and probably not what you’d expect as output.

The stealth loggers can be used in different packages, you just need to make sure you’re calling the «use» function in every package you’re using Log::Log4perl‘s easy services:

    package Bar::Twix;
    use Log::Log4perl qw(:easy);
    sub eat { DEBUG("Twix mjam"); }

    package Bar::Mars;
    use Log::Log4perl qw(:easy);
    sub eat { INFO("Mars mjam"); }

    package main;

    use Log::Log4perl qw(:easy);

    Log::Log4perl->easy_init( { level    => $DEBUG,
                                file     => ">>test.log",
                                category => "Bar::Twix",
                                layout   => '%F{1}-%L-%M: %m%n' },
                              { level    => $DEBUG,
                                file     => "STDOUT",
                                category => "Bar::Mars",
                                layout   => '%m%n' },
                            );
    Bar::Twix::eat();
    Bar::Mars::eat();

As shown above, easy_init() will take any number of different logger definitions as hash references.

Also, stealth loggers feature the functions LOGWARN(), LOGDIE(), and LOGEXIT(), combining a logging request with a subsequent Perl warn() or die() or exit() statement. So, for example

    if($all_is_lost) {
        LOGDIE("Terrible Problem");
    }

will log the message if the package’s logger is at least FATAL but die() (including the traditional output to STDERR) in any case afterwards.

See «Log and die or warn» for the similar logdie() and logwarn() functions of regular (i.e non-stealth) loggers.

Similarily, LOGCARP(), LOGCLUCK(), LOGCROAK(), and LOGCONFESS() are provided in :easy mode, facilitating the use of logcarp(), logcluck(), logcroak(), and logconfess() with stealth loggers.

When using Log::Log4perl in easy mode, please make sure you understand the implications of «Pitfalls with Categories».

By the way, these convenience functions perform exactly as fast as the standard Log::Log4perl logger methods, there’s no performance penalty whatsoever.

Nested Diagnostic Context (NDC)

If you find that your application could use a global (thread-specific) data stack which your loggers throughout the system have easy access to, use Nested Diagnostic Contexts (NDCs). Also check out «Mapped Diagnostic Context (MDC)», this might turn out to be even more useful.

For example, when handling a request of a web client, it’s probably useful to have the user’s IP address available in all log statements within code dealing with this particular request. Instead of passing this piece of data around between your application functions, you can just use the global (but thread-specific) NDC mechanism. It allows you to push data pieces (scalars usually) onto its stack via

    Log::Log4perl::NDC->push("San");
    Log::Log4perl::NDC->push("Francisco");

and have your loggers retrieve them again via the «%x» placeholder in the PatternLayout. With the stack values above and a PatternLayout format like «%x %m%n», the call

    $logger->debug("rocks");

will end up as

    San Francisco rocks

in the log appender.

The stack mechanism allows for nested structures. Just make sure that at the end of the request, you either decrease the stack one by one by calling

    Log::Log4perl::NDC->pop();
    Log::Log4perl::NDC->pop();

or clear out the entire NDC stack by calling

    Log::Log4perl::NDC->remove();

Even if you should forget to do that, Log::Log4perl won’t grow the stack indefinitely, but limit it to a maximum, defined in Log::Log4perl::NDC (currently 5). A call to push() on a full stack will just replace the topmost element by the new value.

Again, the stack is always available via the «%x» placeholder in the Log::Log4perl::Layout::PatternLayout class whenever a logger fires. It will replace «%x» by the blank-separated list of the values on the stack. It does that by just calling

    Log::Log4perl::NDC->get();

internally. See details on how this standard log4j feature is implemented in Log::Log4perl::NDC.

Mapped Diagnostic Context (MDC)

Just like the previously discussed NDC stores thread-specific information in a stack structure, the MDC implements a hash table to store key/value pairs in.

The static method

    Log::Log4perl::MDC->put($key, $value);

stores $value under a key $key, with which it can be retrieved later (possibly in a totally different part of the system) by calling the get method:

    my $value = Log::Log4perl::MDC->get($key);

If no value has been stored previously under $key, the get method will return undef.

Typically, MDC values are retrieved later on via the "%X{...}" placeholder in Log::Log4perl::Layout::PatternLayout. If the get() method returns undef, the placeholder will expand to the string [undef].

An application taking a web request might store the remote host like

    Log::Log4perl::MDC->put("remote_host", $r->headers("HOST"));

at its beginning and if the appender’s layout looks something like

    log4perl.appender.Logfile.layout.ConversionPattern = %X{remote_host}: %m%n

then a log statement like

   DEBUG("Content delivered");

will log something like

   adsl-63.dsl.snf.pacbell.net: Content delivered 

later on in the program.

For details, please check Log::Log4perl::MDC.

Sometimes scripts need to be deployed in environments without having Log::Log4perl installed yet. On the other hand, you don’t want to live without your Log4perl statements — they’re gonna come in handy later.

So, just deploy your script with Log4perl statements commented out with the pattern ###l4p, like in

    ###l4p DEBUG "It works!";
    # ...
    ###l4p INFO "Really!";

If Log::Log4perl is available, use the :resurrect tag to have Log4perl resurrect those buried statements before the script starts running:

    use Log::Log4perl qw(:resurrect :easy);

    ###l4p Log::Log4perl->easy_init($DEBUG);
    ###l4p DEBUG "It works!";
    # ...
    ###l4p INFO "Really!";

This will have a source filter kick in and indeed print

    2004/11/18 22:08:46 It works!
    2004/11/18 22:08:46 Really!

In environments lacking Log::Log4perl, just comment out the first line and the script will run nevertheless (but of course without logging):

    # use Log::Log4perl qw(:resurrect :easy);

    ###l4p Log::Log4perl->easy_init($DEBUG);
    ###l4p DEBUG "It works!";
    # ...
    ###l4p INFO "Really!";

because everything’s a regular comment now. Alternatively, put the magic Log::Log4perl comment resurrection line into your shell’s PERL5OPT environment variable, e.g. for bash:

    set PERL5OPT=-MLog::Log4perl=:resurrect,:easy
    export PERL5OPT

This will awaken the giant within an otherwise silent script like the following:

    #!/usr/bin/perl

    ###l4p Log::Log4perl->easy_init($DEBUG);
    ###l4p DEBUG "It works!";

As of Log::Log4perl 1.12, you can even force all modules loaded by a script to have their hidden Log4perl statements resurrected. For this to happen, load Log::Log4perl::Resurrector before loading any modules:

    use Log::Log4perl qw(:easy);
    use Log::Log4perl::Resurrector;

    use Foobar; # All hidden Log4perl statements in here will
                # be uncommented before Foobar gets loaded.

    Log::Log4perl->easy_init($DEBUG);
    ...

Check the Log::Log4perl::Resurrector manpage for more details.

Access defined appenders

All appenders defined in the configuration file or via Perl code can be retrieved by the appender_by_name() class method. This comes in handy if you want to manipulate or query appender properties after the Log4perl configuration has been loaded via init().

Note that internally, Log::Log4perl uses the Log::Log4perl::Appender wrapper class to control the real appenders (like Log::Log4perl::Appender::File or Log::Dispatch::FileRotate). The Log::Log4perl::Appender class has an appender attribute, pointing to the real appender.

The reason for this is that external appenders like Log::Dispatch::FileRotate don’t support all of Log::Log4perl’s appender control mechanisms (like appender thresholds).

The previously mentioned method appender_by_name() returns a reference to the real appender object. If you want access to the wrapper class (e.g. if you want to modify the appender’s threshold), use the hash $Log::Log4perl::Logger::APPENDER_BY_NAME{...} instead, which holds references to all appender wrapper objects.

Modify appender thresholds

To set an appender’s threshold, use its threshold() method:

    $app->threshold( $FATAL );

To conveniently adjust all appender thresholds (e.g. because a script uses more_logging()), use

       # decrease thresholds of all appenders
    Log::Log4perl->appender_thresholds_adjust(-1);

This will decrease the thresholds of all appenders in the system by one level, i.e. WARN becomes INFO, INFO becomes DEBUG, etc. To only modify selected ones, use

       # decrease thresholds of selected appenders
    Log::Log4perl->appender_thresholds_adjust(-1, ['AppName1', ...]);

and pass the names of affected appenders in a ref to an array.

Advanced configuration within Perl

Initializing Log::Log4perl can certainly also be done from within Perl. At last, this is what Log::Log4perl::Config does behind the scenes. Log::Log4perl’s configuration file parsers are using a publically available API to set up Log::Log4perl’s categories, appenders and layouts.

Here’s an example on how to configure two appenders with the same layout in Perl, without using a configuration file at all:

  ########################
  # Initialization section
  ########################
  use Log::Log4perl;
  use Log::Log4perl::Layout;
  use Log::Log4perl::Level;

     # Define a category logger
  my $log = Log::Log4perl->get_logger("Foo::Bar");

     # Define a layout
  my $layout = Log::Log4perl::Layout::PatternLayout->new("[%r] %F %L %m%n");

     # Define a file appender
  my $file_appender = Log::Log4perl::Appender->new(
                          "Log::Log4perl::Appender::File",
                          name      => "filelog",
                          filename  => "/tmp/my.log");

     # Define a stdout appender
  my $stdout_appender =  Log::Log4perl::Appender->new(
                          "Log::Log4perl::Appender::Screen",
                          name      => "screenlog",
                          stderr    => 0);

     # Define a mixed stderr/stdout appender
  my $mixed_stdout_stderr_appender = Log::Log4perl::Appender->new(
                          "Log::Log4perl::Appender::Screen",
                          name      => "screenlog",
                          stderr    => { ERROR => 1, FATAL => 1 });

     # Have both appenders use the same layout (could be different)
  $stdout_appender->layout($layout);
  $file_appender->layout($layout);

  $log->add_appender($stdout_appender);
  $log->add_appender($file_appender);
  $log->level($INFO);

Please note the class of the appender object is passed as a string to Log::Log4perl::Appender in the first argument. Behind the scenes, Log::Log4perl::Appender will create the necessary Log::Log4perl::Appender::* (or Log::Dispatch::*) object and pass along the name value pairs we provided to Log::Log4perl::Appender->new() after the first argument.

The name value is optional and if you don’t provide one, Log::Log4perl::Appender->new() will create a unique one for you. The names and values of additional parameters are dependent on the requirements of the particular appender class and can be looked up in their manual pages.

A side note: In case you’re wondering if Log::Log4perl::Appender->new() will also take care of the min_level argument to the Log::Dispatch::* constructors called behind the scenes — yes, it does. This is because we want the Log::Dispatch objects to blindly log everything we send them (debug is their lowest setting) because we in Log::Log4perl want to call the shots and decide on when and what to log.

The call to the appender’s layout() method specifies the format (as a previously created Log::Log4perl::Layout::PatternLayout object) in which the message is being logged in the specified appender. If you don’t specify a layout, the logger will fall back to Log::Log4perl::SimpleLayout, which logs the debug level, a hyphen (-) and the log message.

Layouts are objects, here’s how you create them:

        # Create a simple layout
    my $simple = Log::Log4perl::SimpleLayout();

        # create a flexible layout:
        # ("yyyy/MM/dd hh:mm:ss (file:lineno)> messagen")
    my $pattern = Log::Log4perl::Layout::PatternLayout("%d (%F:%L)> %m%n");

Every appender has exactly one layout assigned to it. You assign the layout to the appender using the appender’s layout() object:

    my $app =  Log::Log4perl::Appender->new(
                  "Log::Log4perl::Appender::Screen",
                  name      => "screenlog",
                  stderr    => 0);

        # Assign the previously defined flexible layout
    $app->layout($pattern);

        # Add the appender to a previously defined logger
    $logger->add_appender($app);

        # ... and you're good to go!
    $logger->debug("Blah");
        # => "2002/07/10 23:55:35 (test.pl:207)> Blahn"

It’s also possible to remove appenders from a logger:

    $logger->remove_appender($appender_name);

will remove an appender, specified by name, from a given logger. Please note that this does not remove an appender from the system.

To eradicate an appender from the system, you need to call Log::Log4perl->eradicate_appender($appender_name) which will first remove the appender from every logger in the system and then will delete all references Log4perl holds to it.

To remove a logger from the system, use Log::Log4perl->remove_logger($logger). After the remaining reference $logger goes away, the logger will self-destruct. If the logger in question is a stealth logger, all of its convenience shortcuts (DEBUG, INFO, etc) will turn into no-ops.

How about Log::Dispatch::Config?

Tatsuhiko Miyagawa’s Log::Dispatch::Config is a very clever simplified logger implementation, covering some of the log4j functionality. Among the things that Log::Log4perl can but Log::Dispatch::Config can’t are:

  • You can’t assign categories to loggers. For small systems that’s fine, but if you can’t turn off and on detailed logging in only a tiny subsystem of your environment, you’re missing out on a majorly useful log4j feature.

  • Defining appender thresholds. Important if you want to solve problems like «log all messages of level FATAL to STDERR, plus log all DEBUG messages in Foo::Bar to a log file». If you don’t have appenders thresholds, there’s no way to prevent cluttering STDERR with DEBUG messages.

  • PatternLayout specifications in accordance with the standard (e.g. «%d{HH:mm}»).

Bottom line: Log::Dispatch::Config is fine for small systems with simple logging requirements. However, if you’re designing a system with lots of subsystems which you need to control independently, you’ll love the features of Log::Log4perl, which is equally easy to use.

Using Log::Log4perl with wrapper functions and classes

If you don’t use Log::Log4perl as described above, but from a wrapper function, the pattern layout will generate wrong data for %F, %C, %L, and the like. Reason for this is that Log::Log4perl‘s loggers assume a static caller depth to the application that’s using them.

If you’re using one (or more) wrapper functions, Log::Log4perl will indicate where your logger function called the loggers, not where your application called your wrapper:

    use Log::Log4perl qw(:easy);
    Log::Log4perl->easy_init({ level => $DEBUG, 
                               layout => "%M %m%n" });

    sub mylog {
        my($message) = @_;

        DEBUG $message;
    }

    sub func {
        mylog "Hello";
    }

    func();

prints

    main::mylog Hello

but that’s probably not what your application expects. Rather, you’d want

    main::func Hello

because the func function called your logging function.

But don’t despair, there’s a solution: Just register your wrapper package with Log4perl beforehand. If Log4perl then finds that it’s being called from a registered wrapper, it will automatically step up to the next call frame.

    Log::Log4perl->wrapper_register(__PACKAGE__);

    sub mylog {
        my($message) = @_;

        DEBUG $message;
    }

Alternatively, you can increase the value of the global variable $Log::Log4perl::caller_depth (defaults to 0) by one for every wrapper that’s in between your application and Log::Log4perl, then Log::Log4perl will compensate for the difference:

    sub mylog {
        my($message) = @_;

        local $Log::Log4perl::caller_depth =
              $Log::Log4perl::caller_depth + 1;
        DEBUG $message;
    }

Also, note that if you’re writing a subclass of Log4perl, like

    package MyL4pWrapper;
    use Log::Log4perl;
    our @ISA = qw(Log::Log4perl);

and you want to call get_logger() in your code, like

    use MyL4pWrapper;

    sub get_logger {
        my $logger = Log::Log4perl->get_logger();
    }

then the get_logger() call will get a logger for the MyL4pWrapper category, not for the package calling the wrapper class as in

    package UserPackage;
    my $logger = MyL4pWrapper->get_logger();

To have the above call to get_logger return a logger for the «UserPackage» category, you need to tell Log4perl that «MyL4pWrapper» is a Log4perl wrapper class:

    use MyL4pWrapper;
    Log::Log4perl->wrapper_register(__PACKAGE__);

    sub get_logger {
          # Now gets a logger for the category of the calling package
        my $logger = Log::Log4perl->get_logger();
    }

This feature works both for Log4perl-relaying classes like the wrapper described above, and for wrappers that inherit from Log4perl use Log4perl’s get_logger function via inheritance, alike.

Access to Internals

The following methods are only of use if you want to peek/poke in the internals of Log::Log4perl. Be careful not to disrupt its inner workings.

Log::Log4perl->appenders()

To find out which appenders are currently defined (not only for a particular logger, but overall), a appenders() method is available to return a reference to a hash mapping appender names to their Log::Log4perl::Appender object references.

Dirty Tricks

infiltrate_lwp()

The famous LWP::UserAgent module isn’t Log::Log4perl-enabled. Often, though, especially when tracing Web-related problems, it would be helpful to get some insight on what’s happening inside LWP::UserAgent. Ideally, LWP::UserAgent would even play along in the Log::Log4perl framework.

A call to Log::Log4perl->infiltrate_lwp() does exactly this. In a very rude way, it pulls the rug from under LWP::UserAgent and transforms its debug/conn messages into debug() calls of loggers of the category "LWP::UserAgent". Similarily, LWP::UserAgent‘s trace messages are turned into Log::Log4perl‘s info() method calls. Note that this only works for LWP::UserAgent versions < 5.822, because this (and probably later) versions miss debugging functions entirely.

Suppressing ‘duplicate’ LOGDIE messages

If a script with a simple Log4perl configuration uses logdie() to catch errors and stop processing, as in

    use Log::Log4perl qw(:easy) ;
    Log::Log4perl->easy_init($DEBUG);
    
    shaky_function() or LOGDIE "It failed!";

there’s a cosmetic problem: The message gets printed twice:

    2005/07/10 18:37:14 It failed!
    It failed! at ./t line 12

The obvious solution is to use LOGEXIT() instead of LOGDIE(), but there’s also a special tag for Log4perl that suppresses the second message:

    use Log::Log4perl qw(:no_extra_logdie_message);

This causes logdie() and logcroak() to call exit() instead of die(). To modify the script exit code in these occasions, set the variable $Log::Log4perl::LOGEXIT_CODE to the desired value, the default is 1.

Redefine values without causing errors

Log4perl’s configuration file parser has a few basic safety mechanisms to make sure configurations are more or less sane.

One of these safety measures is catching redefined values. For example, if you first write

    log4perl.category = WARN, Logfile

and then a couple of lines later

    log4perl.category = TRACE, Logfile

then you might have unintentionally overwritten the first value and Log4perl will die on this with an error (suspicious configurations always throw an error). Now, there’s a chance that this is intentional, for example when you’re lumping together several configuration files and actually want the first value to overwrite the second. In this case use

    use Log::Log4perl qw(:nostrict);

to put Log4perl in a more permissive mode.

Prevent croak/confess from stringifying

The logcroak/logconfess functions stringify their arguments before they pass them to Carp’s croak/confess functions. This can get in the way if you want to throw an object or a hashref as an exception, in this case use:

    $Log::Log4perl::STRINGIFY_DIE_MESSAGE = 0;

    eval {
          # throws { foo => "bar" }
          # without stringification
        $logger->logcroak( { foo => "bar" } );
    };

EXAMPLE

A simple example to cut-and-paste and get started:

    use Log::Log4perl qw(get_logger);
    
    my $conf = q(
    log4perl.category.Bar.Twix         = WARN, Logfile
    log4perl.appender.Logfile          = Log::Log4perl::Appender::File
    log4perl.appender.Logfile.filename = test.log
    log4perl.appender.Logfile.layout = 
        Log::Log4perl::Layout::PatternLayout
    log4perl.appender.Logfile.layout.ConversionPattern = %d %F{1} %L> %m %n
    );
    
    Log::Log4perl::init($conf);
    
    my $logger = get_logger("Bar::Twix");
    $logger->error("Blah");

This will log something like

    2002/09/19 23:48:15 t1 25> Blah 

to the log file test.log, which Log4perl will append to or create it if it doesn’t exist already.

INSTALLATION

If you want to use external appenders provided with Log::Dispatch, you need to install Log::Dispatch (2.00 or better) from CPAN, which itself depends on Attribute-Handlers and Params-Validate. And a lot of other modules, that’s the reason why we’re now shipping Log::Log4perl with its own standard appenders and only if you wish to use additional ones, you’ll have to go through the Log::Dispatch installation process.

Log::Log4perl needs Test::More, Test::Harness and File::Spec, but they already come with fairly recent versions of perl. If not, everything’s automatically fetched from CPAN if you’re using the CPAN shell (CPAN.pm), because they’re listed as dependencies.

Time::HiRes (1.20 or better) is required only if you need the fine-grained time stamps of the %r parameter in Log::Log4perl::Layout::PatternLayout.

Manual installation works as usual with

    perl Makefile.PL
    make
    make test
    make install

DEVELOPMENT

Log::Log4perl is still being actively developed. We will always make sure the test suite (approx. 500 cases) will pass, but there might still be bugs. please check http://github.com/mschilli/log4perl for the latest release. The api has reached a mature state, we will not change it unless for a good reason.

Bug reports and feedback are always welcome, just email them to our mailing list shown in the AUTHORS section. We’re usually addressing them immediately.

REFERENCES

[1]

Michael Schilli, «Retire your debugger, log smartly with Log::Log4perl!», Tutorial on perl.com, 09/2002, http://www.perl.com/pub/a/2002/09/11/log4perl.html

[2]

Ceki Gülcü, «Short introduction to log4j», http://logging.apache.org/log4j/1.2/manual.html

[3]

Vipan Singla, «Don’t Use System.out.println! Use Log4j.», http://www.vipan.com/htdocs/log4jhelp.html

[4]

The Log::Log4perl project home page: http://log4perl.com

SEE ALSO

Log::Log4perl::Config, Log::Log4perl::Appender, Log::Log4perl::Layout::PatternLayout, Log::Log4perl::Layout::SimpleLayout, Log::Log4perl::Level, Log::Log4perl::JavaMap Log::Log4perl::NDC,

Please contribute patches to the project on Github:

    http://github.com/mschilli/log4perl

Send bug reports or requests for enhancements to the authors via our

MAILING LIST (questions, bug reports, suggestions/patches): log4perl-devel@lists.sourceforge.net

Authors (please contact them via the list above, not directly): Mike Schilli <m@perlmeister.com>, Kevin Goess <cpan@goess.org>

Contributors (in alphabetical order): Ateeq Altaf, Cory Bennett, Jens Berthold, Jeremy Bopp, Hutton Davidson, Chris R. Donnelly, Matisse Enzer, Hugh Esco, Anthony Foiani, James FitzGibbon, Carl Franks, Dennis Gregorovic, Andy Grundman, Paul Harrington, Alexander Hartmaier, David Hull, Robert Jacobson, Jason Kohles, Jeff Macdonald, Markus Peter, Brett Rann, Peter Rabbitson, Erik Selberg, Aaron Straup Cope, Lars Thegler, David Viner, Mac Yang.

LICENSE

Copyright 2002-2013 by Mike Schilli <m@perlmeister.com> and Kevin Goess <cpan@goess.org>.

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

Sys::Syslog — это интерфейс к программе UNIX syslog(3) . Вызовите syslog() с приоритетом строки и списком аргументов printf() точно так же, как syslog(3) .

По умолчанию Sys::Syslog экспортирует символы из тега :standard .

openlog ($ идент, $ логопт, $ объект)

Открывает системный журнал. $ident добавляется к каждому сообщению. $logopt содержит ноль или более параметров, описанных ниже. $facility указывает часть системы, о которой нужно сообщить, например, LOG_USER или LOG_LOCAL0 : см. «Средства» для получения списка хорошо известных средств и документацию вашего syslog(3) журнала (3) для средств, доступных в вашей системе. Проверьте «СМОТРИ ТАКЖЕ» для получения полезных ссылок. Функцию можно указать в виде строки или числового макроса.

Эта функция перестанет работать,если не сможет соединиться с демоном syslog.

Обратите внимание, что openlog() теперь принимает три аргумента, как и openlog(3) .

Вы должны использовать openlog() перед вызовом syslog() .

Options

  • cons — этот параметр игнорируется, поскольку механизм аварийного переключения автоматически отключается до консоли, если все другие носители не работают.

  • ndelay — немедленно открыть соединение (обычно соединение открывается при регистрации первого сообщения).

  • noeol — если установлено значение true, к сообщению не будет добавляться символ конца строки ( n ). Это может быть полезно для некоторых демонов системного журнала. Добавлено в Sys::Syslog 0.29.

  • nofatal — если установлено значение true, openlog() и syslog() будут выдавать предупреждения, а не отключаться, если не удается установить соединение с системным журналом. Добавлено в Sys::Syslog 0.15.

  • nonul — если установлено значение true, к сообщению не будет NUL символ NUL ( ). Это может быть полезно для некоторых демонов системного журнала. Добавлено в Sys::Syslog 0.29.

  • nowait — не дожидайтесь появления дочерних процессов, которые могли быть созданы при регистрации сообщения. (Библиотека GNU C не создает дочерний процесс, поэтому этот параметр не влияет на Linux.)

  • perror — Запишите сообщение в стандартный вывод ошибок, а также в системный журнал. Добавлено в Sys::Syslog 0.22.

  • pid — Включать PID в каждое сообщение.

Examples

Откройте системный журнал с параметрами ndelay и pid , а также LOCAL0 :

openlog($name, "ndelay,pid", "local0");

То же самое, но на этот раз с использованием макроса, соответствующего LOCAL0 :

openlog($name, "ndelay,pid", LOG_LOCAL0);
syslog($priority, $message)
syslog ($ приоритет, $ формат, @args)

Если позволяет $priority , записывает $message или sprintf($format, @args) с добавлением, что %m в $ message или $format заменяется на "$!" (последнее сообщение об ошибке).

$priority может указывать уровень или уровень и средство. Уровни и объекты могут быть заданы в виде строк или макросов. При использовании eventlog механизма, приоритеты DEBUG и INFO отображаются на тип события informational , NOTICE и WARNING для warning и ERR в EMERG к error .

Если вы не использовали openlog() до использования syslog() , syslog() попытается угадать $ident , извлекая кратчайший префикс $format который заканчивается на ":" .

Examples

syslog("info", $message);
syslog(LOG_INFO, $message);


syslog("info|local0", $message);
syslog(LOG_INFO|LOG_LOCAL0, $message);
Note

Sys::Syslog версии v0.07 и старше передавал $message в качестве строки форматирования в sprintf() даже если аргументы форматирования не были предоставлены. Если код, вызывающий syslog() может выполняться с более старыми версиями этого модуля, убедитесь, что функция вызывается как syslog($priority, "%s", $message) вместо syslog($priority, $message) . Это защищает от враждебных последовательностей форматирования, которые могут появиться, если $ message содержит испорченные данные.

setlogmask($mask_priority)

Устанавливает маску журнала для текущего процесса на $mask_priority и возвращает старую маску. Если аргумент маски равен 0, текущая маска журнала не изменяется. См. «Уровни» для получения списка доступных уровней. Вы можете использовать LOG_UPTO() чтобы разрешить все уровни до заданного приоритета (но она принимает только числовые макросы в качестве аргументов).

Examples

Только ошибки журнала:

setlogmask( LOG_MASK(LOG_ERR) );

Регистрируйте все,кроме информационных сообщений:

setlogmask( ~(LOG_MASK(LOG_INFO)) );

Журнал критических сообщений,ошибок и предупреждений:

setlogmask( LOG_MASK(LOG_CRIT)
          | LOG_MASK(LOG_ERR)
          | LOG_MASK(LOG_WARNING) );

Записывайте все сообщения до отладки:

setlogmask( LOG_UPTO(LOG_DEBUG) );
setlogsock()

Устанавливает тип сокета и параметры, которые будут использоваться для следующего вызова openlog() или syslog() . Возвращает true при успехе, undef при неудаче.

Будучи перл-специфической,эта функция эволюционировала во времени.В настоящее время ее можно назвать следующим образом:

  • setlogsock($sock_type)

  • setlogsock($sock_type, $stream_location) (добавлено в Perl 5.004_02)

  • setlogsock($sock_type, $stream_location, $sock_timeout) (добавлено в Sys::Syslog 0.25)

  • setlogsock(%options) (добавлено в Sys::Syslog 0.28)

Доступны следующие варианты:

  • type — эквивалент $sock_type , выбирает тип сокета (или «механизм»). Можно передать ссылку на массив, чтобы указать несколько механизмов, которые нужно попробовать, в заданном порядке.

  • path — эквивалент $stream_location , устанавливает расположение потока. По умолчанию используется стандартное расположение Unix или _PATH_LOG .

  • timeout — эквивалент $sock_timeout , устанавливает тайм-аут сокета в секундах. По умолчанию 0 во всех системах, кроме Mac OS X, где он установлен на 0,25 секунды.

  • host — устанавливает имя хоста для отправки сообщений. По умолчанию используется локальный хост.

  • port — устанавливает порт TCP или UDP для подключения. По умолчанию используется первый стандартный порт системного журнала, доступный в системе.

Имеющиеся механизмы:

  • "native" — используйте собственные функции C из вашей библиотеки syslog(3) (добавленной в Sys::Syslog 0.15).

  • "eventlog" событий » — отправлять сообщения в журнал событий Win32 (только Win32; добавлено в Sys::Syslog 0.19).

  • "tcp" — подключиться к сокету TCP, к службе syslog/tcp или syslogng/tcp . См. Также параметры host , port и timeout .

  • "udp" — подключиться к UDP-сокету в сервисе syslog/udp . См. Также параметры host , port и timeout .

  • "inet" — подключиться к сокету INET, TCP или UDP, в указанном порядке. См. Также параметры host , port и timeout .

  • "unix" — подключиться к сокету домена UNIX (в некоторых системах символьное специальное устройство). Имя этого сокета задается параметром path или, если он не _PATH_LOG , значением, возвращаемым макросом _PATH_LOG (если ваша система определяет его),/dev/logor/dev/conslog, в зависимости от того, что доступно для записи.

  • "stream" — подключиться к потоку, указанному параметром path или, если он не указан , значением, возвращаемым _PATH_LOG (если ваша система определяет его),/dev/logor/dev/conslog, в зависимости от того, что доступно для записи. Например, система Solaris и IRIX может предпочесть "stream" вместо "unix" .

  • "pipe" — подключиться к именованному каналу, указанному в параметре path , или, если он не указан , к значению, возвращаемому _PATH_LOG (если ваша система определяет его), или/dev/log(добавлено в Sys::Syslog 0.21). HP-UX — это система, в которой используется такой именованный канал.

  • "console" — отправлять сообщения прямо в консоль, как для опции "cons" openlog() .

По умолчанию используется native , tcp , udp , unix , pipe , stream , console . В системах с Win32 API eventlog будет добавлен в качестве первого механизма для проверки доступности Win32::EventLog .

Предоставление недопустимого значения $sock_type будет croak .

Examples

Выберите механизм UDP-розетки:

setlogsock("udp");

Отправка сообщений с помощью механизма TCP сокетов на пользовательском порту:

setlogsock({ type => "tcp", port => 2486 });

Отправка сообщений на удаленный хост с помощью механизма TCP сокетов:

setlogsock({ type => "tcp", host => $loghost });

Попробуйте «родной»,UDP сокет,а затем механизмы UNIX доменных сокетов:

setlogsock(["native", "udp", "unix"]);
Note

Теперь, когда «собственный» механизм поддерживается Sys::Syslog и выбран по умолчанию, использование функции setlogsock() не рекомендуется, поскольку другие механизмы менее переносимы между операционными системами. Авторам модулей и программ, которые используют эту функцию, особенно ее культовой формы setlogsock("unix") , рекомендуется удалять все ее вхождения, если они специально не хотят использовать данный механизм (например, TCP или UDP для подключения к удаленному компьютеру). хозяин).

closelog()

Закрывает лог-файл и возвращает true on success.

Perl is a cross-platform, open-source computer programming language that is extensively used in both the commercial and private sectors. Perl is popular among Web developers due to its adaptable, ever-evolving text-processing and problem-solving capabilities. Although Perl was initially developed for text editing, its flexibility makes it a versatile tool for a variety of tasks.

We’ve looked at some of the things that might create frequent mistakes, but not everything is a common issue. If you’re encountering troubles and none of the options are working for CGI, you’ll need to conduct some research. In this part, we’ll look at various tools that can assist you in locating the cause of the problem. Here’s a quick rundown of the actions you can take:

  • Using the -c switch, you may check the syntax of your scripts.
  • Examine the error logs on the webserver.
  • Use the command line to run your script. Dumping variables to the browser allows you to test their values.
  • Make use of an interactive debugger.

Verifying Syntax

If your code does not parse or compile, it will never execute correctly. So, before you test your scripts in the browser, make a practice of testing them using the -c flag from the command line, and while you’re doing it, have it checked for warnings using the -w flag. Remember that if you use taint mode (which you probably do with all of your scripts), you must also pass the -T parameter to avoid the following error: myScript.cgi -wc perl The “-T” option is no longer available. As a result, use the 

perl -wcT calendar.cgi

Examine the Error Logs

Errors are often reported to STDERR, and on certain web servers, everything produced to STDERR while a CGI script is executing shows up in the error logs. When you have an issue, you may typically find a lot of important information by reviewing these logs. This file may be found at:

/usr/local/apache/logs/error log or /usr/var/logs/httpd/error log with Apache. 

Errors are appended to the bottom of the log; you should keep an eye on it while you test your CGI script. If you execute the tail command with the -f option

$ tail -f /usr/local/apache/logs/error_log

Scripts Executed from the Command Line

After your scripts have passed a syntax check, you may try running them from the command line. Because CGI programs rely heavily on environment variables, you can manually configure these variables before running your script

$ export HTTP_COOKIE=”user_id=abc123″ 

$ export QUERY_STRING=”month=jan&year=2001″ 

$ export REQUEST_METHOD=”GET” 

$ ./calendar.cgi

Debugger for Perl

You’ll end up in an interactive session if you run Perl with the -d switch. Regrettably, this implies that the debugger can only be used via the command line. Although this is not the typical environment for CGI scripts, as we showed before, it is not straightforward to replicate the CGI environment. Saving a CGI object to a query file, initializing any other environment variables you might require, such as cookies, and then running your CGI script like this is the best method to do it.

$perl -dT calendar.cgi 

Loading DB routines from perl5db.pl version 1 

Emacs support available

Enter h or `h h’ for help. 

main::(Dev:Pseudo:7): my $q = new CGI; DB<1>

At first, the debugger may appear scary, but it is really powerful. 

The table provides a quick overview of all the fundamental commands you’ll need to troubleshoot a script to get you started. Although many more tools are available, you can debug all of your CGI scripts with only these instructions. To understand how to navigate the debugger, practice stepping through programs that you already know work properly. Because the debugger does not modify your files, you cannot break a working script by inputting an incorrect command.

Command Description
s

Step; Perl steps into any subroutines and executes the line listed above the prompt. It’s worth noting that evaluating a line with several instructions may take a few steps.

n

Following that, Perl runs the line listed above the prompt, skipping any subroutines (they still run; Perl waits for them to finish before continuing)

breakpoint

Continue until the program ends or the next breakpoint is reached, whichever comes first.

c 123 Continue until you reach line 123, which must include a command (it cannot be a comment, blank line, the second half of a command, etc.)
b

Set a breakpoint at the current line; breakpoints stop the execution of code that has been halted by c.

b 123

Place a breakpoint on line 123, which must include a command (it cannot be a comment, blank line, the second half of command, etc.).

b mySub

Set a breakpoint on my sub’s first executable line.

d

Removes a breakpoint from the current line and accepts the same parameters as b.

D

Breakpoint delete

Conclusion

There are two requirements for using ptkdb. You’ll need an X Window server first; the X Window System is bundled with most Unix and comparable systems, and commercial versions are also available for other operating systems. Second, the webserver must contain the Tk.pm module, which needs Tk and is accessible on CPAN. Tk is a graphics library that comes with the Tcl programming language. 

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Pfro error что это
  • Pfro error delete operation
  • Pfe ошибка стиральная машина daewoo
  • Phoenix sct flash error 233
  • Phoenix sct flash error 222

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии