Consolidation and extended test runs
[kivitendo-erp.git] / SL / LXDebug.pm
index abbb035..553ab50 100644 (file)
@@ -8,33 +8,30 @@ use constant QUERY              =>  1 << 3;
 use constant TRACE              =>  1 << 4;
 use constant BACKTRACE_ON_ERROR =>  1 << 5;
 use constant REQUEST_TIMER      =>  1 << 6;
-use constant WARN               =>  1 << 7;
-use constant ALL                => (1 << 8) - 1;
-use constant DEVEL              => INFO | QUERY | TRACE | BACKTRACE_ON_ERROR | REQUEST_TIMER;
+use constant REQUEST            =>  1 << 7;
+use constant WARN               =>  1 << 8;
+use constant TRACE2             =>  1 << 9;
+use constant ALL                => (1 << 10) - 1;
+use constant DEVEL              => INFO | DEBUG1 | QUERY | TRACE | BACKTRACE_ON_ERROR | REQUEST_TIMER;
 
 use constant FILE_TARGET   => 0;
 use constant STDERR_TARGET => 1;
 
+use Data::Dumper;
 use POSIX qw(strftime getppid);
 use Time::HiRes qw(gettimeofday tv_interval);
 use YAML;
+use SL::Request ();
 
 use strict;
+use utf8;
 
-my ($data_dumper_available, $text_diff_available);
+my ($text_diff_available);
 
-our $global_level;
-our $watch_form;
+our $global_level = NONE();
+our $watch_form   = 0;
 our $file_name;
 
-BEGIN {
-  eval("use Data::Dumper");
-  $data_dumper_available = $@ ? 0 : 1;
-
-  $global_level      = NONE;
-  $watch_form        = 0;
-}
-
 sub new {
   my $type = shift;
   my $self = {};
@@ -88,7 +85,7 @@ sub enter_sub {
   my $level = shift || 0;
 
   return 1 unless ($global_level & TRACE);          # ignore if traces aren't active
-  return 1 if $level && !($global_level & $level);  # ignore if level of trace isn't active
+  return 1 if $level && !($global_level & TRACE2);  # ignore if level of trace isn't active
 
   my ($package, $filename, $line, $subroutine) = caller(1);
   my ($dummy1, $self_filename, $self_line) = caller(0);
@@ -112,13 +109,13 @@ sub leave_sub {
   my $level = shift || 0;
 
   return 1 unless ($global_level & TRACE);           # ignore if traces aren't active
-  return 1 if $level && !($global_level & $level);   # ignore if level of trace isn't active
+  return 1 if $level && !($global_level & TRACE2);   # ignore if level of trace isn't active
 
   my ($package, $filename, $line, $subroutine) = caller(1);
   my ($dummy1, $self_filename, $self_line) = caller(0);
 
   my $indent = " " x --$self->{"calldepth"};
-  my $time = $self->want_request_timer ? $self->get_request_time : '';
+  my $time = $self->want_request_timer ? $self->get_request_time || '' : '';
 
   if (!defined($package)) {
     $self->_write('sub' . $level, $indent . "/ $time top-level?\n");
@@ -133,10 +130,10 @@ sub show_backtrace {
 
   return 1 unless ($force || ($global_level & BACKTRACE_ON_ERROR));
 
-  $self->message(BACKTRACE_ON_ERROR, "Starting full caller dump:");
+  $self->message(0, "Starting full caller dump:");
   my $level = 0;
   while (my ($dummy, $filename, $line, $subroutine) = caller $level) {
-    $self->message(BACKTRACE_ON_ERROR, "  ${subroutine} from ${filename}:${line}");
+    $self->message(0, "  ${subroutine} from ${filename}:${line}");
     $level++;
   }
 
@@ -156,33 +153,31 @@ sub warn {
 }
 
 sub dump {
-  my ($self, $level, $name, $variable) = @_;
+  my ($self, $level, $name, $variable, %options) = @_;
 
-  if ($data_dumper_available) {
-    my $password;
-    if ($variable && ('Form' eq ref $variable) && defined $variable->{password}) {
-      $password             = $variable->{password};
-      $variable->{password} = 'X' x 8;
-    }
-
-    my $dumper = Data::Dumper->new([$variable]);
-    $dumper->Sortkeys(1);
-    $self->message($level, "dumping ${name}:\n" . $dumper->Dump());
+  my $password;
+  if ($variable && ('Form' eq ref $variable) && defined $variable->{password}) {
+    $password             = $variable->{password};
+    $variable->{password} = 'X' x 8;
+  }
 
-    $variable->{password} = $password if (defined $password);
+  my $dumper = Data::Dumper->new([$variable]);
+  $dumper->Sortkeys(1);
+  $dumper->Indent(2);
+  $dumper->$_($options{$_}) for keys %options;
+  my $output = $dumper->Dump();
+  $self->message($level, "dumping ${name}:\n" . $output);
 
-    # Data::Dumper does not reset the iterator belonging to this hash
-    # if 'Sortkeys' is true. Therefore clear the iterator manually.
-    # See "perldoc -f each".
-    if ($variable && (('HASH' eq ref $variable) || ('Form' eq ref $variable))) {
-      keys %{ $variable };
-    }
+  $variable->{password} = $password if (defined $password);
 
-  } else {
-    $self->message($level,
-                   "dumping ${name}: Data::Dumper not available; "
-                     . "variable cannot be dumped");
+  # Data::Dumper does not reset the iterator belonging to this hash
+  # if 'Sortkeys' is true. Therefore clear the iterator manually.
+  # See "perldoc -f each".
+  if ($variable && (('HASH' eq ref $variable) || ('Form' eq ref $variable))) {
+    keys %{ $variable };
   }
+
+  return $output;
 }
 
 sub dump_yaml {
@@ -219,6 +214,17 @@ sub dump_sql_result {
   $self->message($level, $prefix . sprintf('(%d row%s)', scalar @{ $results }, scalar @{ $results } > 1 ? 's' : ''));
 }
 
+sub dump_object {
+  my ($self, $level, $text, $object) = @_;
+
+  my $copy;
+  if ($object) {
+    $copy->{$_} = $object->$_ for $object->meta->columns;
+  }
+
+  $self->dump($level, $text, $copy);
+}
+
 sub show_diff {
   my ($self, $level, $item1, $item2, %params) = @_;
 
@@ -255,18 +261,25 @@ sub is_tracing_enabled {
 sub _write {
   no warnings;
   my ($self, $prefix, $message) = @_;
-  my $date = strftime("%Y-%m-%d %H:%M:%S $$ [" . getppid() . "] ${prefix}: ", localtime(time()));
+  my @now  = gettimeofday();
+  my $date = strftime("%Y-%m-%d %H:%M:%S." . sprintf('%03d', int($now[1] / 1000)) . " $$ [" . getppid() . "] ${prefix}: ", localtime($now[0]));
   local *FILE;
 
   chomp($message);
+  $self->_write_raw("${date}${message}\n");
+}
 
+sub _write_raw {
+  my ($self, $message) = @_;
+  local *FILE;
   if ((FILE_TARGET == $self->{"target"})
-      && open(FILE, ">>" . $self->{"file"})) {
-    print(FILE "${date}${message}\n");
-    close(FILE);
+      && open(FILE, ">>", $self->{"file"})) {
+    binmode FILE, ":utf8";
+    print FILE $message;
+    close FILE;
 
   } elsif (STDERR_TARGET == $self->{"target"}) {
-    print(STDERR "${date}${message}\n");
+    print STDERR $message;
   }
 }
 
@@ -291,9 +304,14 @@ sub end_request {
 }
 
 sub log_time {
-  my $self = shift;
+  my ($self, @slurp) = @_;
   return 1 unless want_request_timer();
-  $self->_write("time", $self->get_request_time);
+
+  my $now                    = $self->get_request_time;
+  my $diff                   = int((($now - ($self->{previous_log_time} // 0)) * 10_000 + 5) / 10);
+  $self->{previous_log_time} = $now;
+
+  $self->_write("time", "${now}s Δ ${diff}ms" . (@slurp ? " (@slurp)" : ''));
 }
 
 sub get_request_time {
@@ -330,6 +348,44 @@ sub level_by_name {
   return $global_level & $self->_by_name($level);
 }
 
+sub is_request_logging_enabled {
+  my ($self) = @_;
+  return $global_level & REQUEST;
+}
+
+sub add_request_params {
+  my ($self, $key, $value) = @_;
+  return unless $self->is_request_logging_enabled;
+  return if $key =~ /password/;
+
+  push @{ $::request->{debug}{PARAMS} ||= [] }, [ $key => $value ];
+}
+
+sub log_request {
+  my ($self, $type, $controller, $action) = @_;
+  return unless $self->is_request_logging_enabled;
+
+  my $session_id = $::auth->create_or_refresh_session;
+
+  my $template = <<EOL;
+*************************************
+ $ENV{REQUEST_METHOD} $ENV{SCRIPT_NAME}    $session_id ($::myconfig{login})
+   routing: $type, controller: $controller, action: $action
+EOL
+
+  $self->_write('Request', $template);
+
+  my $params = join "\n   ", map {
+    "$_->[0] = $_->[1]"
+  } @{ $::request->{debug}{PARAMS} || [] };
+
+  $self->_write_raw(<<EOL);
+
+ Params
+   $params
+EOL
+}
+
 1;
 __END__
 
@@ -339,11 +395,11 @@ __END__
 
 =head1 NAME
 
-LXDebug - Lx-Office debugging facilities
+LXDebug - kivitendo debugging facilities
 
 =head1 SYNOPSIS
 
-This module provides functions for debugging Lx-Office. An instance is
+This module provides functions for debugging kivitendo. An instance is
 always created as the global variable C<$::lxdebug> at the earliest
 possible moment.
 
@@ -382,7 +438,15 @@ Log all queries executed by the L<SL::DBUtils> utility methods.
 
 =item C<TRACE>
 
-Log sub calls and exits via the L<enter_sub>/L<leave_sub> functions.
+Log sub calls and exits via the L<enter_sub>/L<leave_sub> functions,
+but only if they're called with a log level that is falsish
+(e.g. none, C<undef>, 0).
+
+=item C<TRACE2>
+
+Log sub calls and exits via the L<enter_sub>/L<leave_sub> functions
+even if they're called with a log level of 2. Will only have an effect
+if C<TRACE> is set as well.
 
 =item C<BACKTRACE_ON_ERROR>
 
@@ -406,6 +470,57 @@ Shortcut for C<INFO | QUERY | TRACE | BACKTRACE_ON_ERROR | REQUEST_TIMER>.
 
 =back
 
+=head1 CONFIGURATION
+
+C<SL::LXDebug> gets its configuration from the C<[debug]> section of
+the C<config/kivitendo.conf> configuration file. The available options
+are:
+
+=over 4
+
+=item C<global_level>
+
+A string of log level names that should be activated by
+default. Multiple log levels are separated by C<|>.
+
+=item C<watch_form>
+
+A boolean (C<1> or C<0>). Turns on the C<$::form> watch facility. If
+this is enabled then any key inside C<$::form> can be monitored for
+changes. For example:
+
+  # Start watching 'action'
+  $::form->{"Watchdog::action"} = 1;
+  # Stop watching 'invtotal'
+  $::form->{"Watchdog::invtotal"} = 0;
+
+A log message is written when the watchdog is enabled for a variable
+and for each subsequent change. The log message includes the place
+(file name and line number) of the instruction changing the key.
+
+Note that this entails a performance penalty. Also only the keys
+themselves are monitored -- not the references they point to. E.g. the
+following would not trigger a change:
+
+  $::form->{"Watchdog::some_hash"} = 1;
+  # Does not trigger:
+  $::form->{some_hash}->{some_value} = 42;
+  # This does trigger:
+  $::form->{some_hash} = { something => 'else' };
+
+=item C<keep_temp_files>
+
+A boolean (C<1> or C<0>). If turned on then certain temporary files
+are not removed but kept in the C<users> directory. These include the
+temporary files used during printing, e.g. LaTeX files.
+
+=item C<file_name>
+
+The path and file name of the debug log file. Must be a location
+writeable by the web server process.
+
+=back
+
 =head1 FUNCTIONS
 
 =over 4
@@ -418,8 +533,8 @@ Pairs of these can be put near the beginning/end of a sub. They'll
 cause a trace to be written to the log file if the C<TRACE> level is
 active.
 
-If C<$level> is given then the log messages will only be logged if an
-additional log level C<$level> is active as well.
+If C<$level> is given then the log messages will only be logged if the
+global log level C<TRACE2> is active as well.
 
 =item C<enable_sub_tracing>