paperlined.org
dev > perl > run_in_every_script
document updated 5 days ago, on Nov 1, 2024

run Devel::TraceUse in every script

If you want to automatically run Devel::TraceUse inside every script on a server, paste this into $Config{sitelib}/sitecustomize.pl:

# This runs Devel::TraceUse in EVERY perl script on this server, automatically.
# Log files will be written to /var/tmp/Devel::TraceUse/.


# ---- configuration varables ----

# Record a separate log file for each pid?  (true/false)
my $CONFIG__PER_PID = 0;

# Only record log files for one script?  (blank to record for all scripts)
my $CONFIG__ONLY_ONE_SCRIPT = '/usr/bin/blah';



use File::Spec::Functions;

my $DevelTraceUse_log;
my $zero;           # $0 but an absolute path

BEGIN {
    mkdir '/var/tmp/Devel::TraceUse/';
    chmod 0777, '/var/tmp/Devel::TraceUse/';    # make sure scripts under other users can write to it

    $zero = File::Spec::Functions::rel2abs($0);
    $DevelTraceUse_log = "$zero.user--" . getpwuid($<) . ".log";
    $DevelTraceUse_log =~ s#/#=#g;
    $DevelTraceUse_log = "/var/tmp/Devel::TraceUse/$DevelTraceUse_log";

    # option to record a separate log file per pid
    if ($CONFIG__PER_PID) {
        $DevelTraceUse_log =~ s/\.log$/.pid--$$.log/;
    }

    # mute the "Use -d:TraceUse for more accurate information." message
    $^P = 0x08;

    # Handle the situation where scripts are almost always running, and the
    # most you can do is restart them, leading to an otherwise-constantly
    # zero file-size for the log.
    if (-e $DevelTraceUse_log && -s $DevelTraceUse_log > 0) {
        rename $DevelTraceUse_log, "$DevelTraceUse_log.old";
    }
}


use if (!$CONFIG__ONLY_ONE_SCRIPT || $zero eq $CONFIG__ONLY_ONE_SCRIPT),
      "Devel::TraceUse" => "output:$DevelTraceUse_log";


# make sure that Devel::TraceUse gets called, even when the script dies
BEGIN {
    if ($INC{'Devel/TraceUse.pm'}) {        # in case $ONLY_ONE_SCRIPT is specified
        $SIG{__DIE__} = sub {
            # make sure we're not inside an eval
            return if [caller(1)]->[3] eq '(eval)' || ${^GLOBAL_PHASE} eq 'START' || $^S;
            Devel::TraceUse::dump_result();
        };
    }
}

This will automatically create log files in /var/tmp/Devel::TraceUse/.