Merge branch 'master' of vc.linet-services.de:public/lx-office-erp
[kivitendo-erp.git] / SL / LXDebug.pm
index 7d17aec..2f80cac 100644 (file)
@@ -9,8 +9,9 @@ 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 TRACE2             =>  1 << 8;
+use constant ALL                => (1 << 9) - 1;
+use constant DEVEL              => INFO | DEBUG1 | QUERY | TRACE | BACKTRACE_ON_ERROR | REQUEST_TIMER;
 
 use constant FILE_TARGET   => 0;
 use constant STDERR_TARGET => 1;
@@ -21,7 +22,7 @@ use YAML;
 
 use strict;
 
-my $data_dumper_available;
+my ($data_dumper_available, $text_diff_available);
 
 our $global_level;
 our $watch_form;
@@ -39,6 +40,8 @@ sub new {
   my $type = shift;
   my $self = {};
 
+  _init_globals_from_config();
+
   $self->{"calldepth"}  = 0;
   $self->{"file"}       = $file_name || "/tmp/lx-office-debug.log";
   $self->{"target"}     = FILE_TARGET;
@@ -53,6 +56,22 @@ sub new {
   bless($self, $type);
 }
 
+my $globals_inited_from_config;
+sub _init_globals_from_config {
+  return if $globals_inited_from_config;
+  $globals_inited_from_config = 1;
+
+  my $cfg = $::lx_office_conf{debug} || {};
+
+  $global_level = NONE() if $cfg->{global_level} =~ /NONE/;
+  foreach my $level (grep { $_} split(m/\s+/, $cfg->{global_level})) {
+    $global_level |= eval "${level}()";
+  }
+
+  $watch_form = $cfg->{watch_form};
+  $file_name  = $cfg->{file_name} || "/tmp/lx-office-debug.log";
+}
+
 sub set_target {
   my ($self, $target, $file) = @_;
 
@@ -70,7 +89,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);
@@ -94,7 +113,7 @@ 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);
@@ -201,6 +220,24 @@ sub dump_sql_result {
   $self->message($level, $prefix . sprintf('(%d row%s)', scalar @{ $results }, scalar @{ $results } > 1 ? 's' : ''));
 }
 
+sub show_diff {
+  my ($self, $level, $item1, $item2, %params) = @_;
+
+  if (!$self->_load_text_diff) {
+    $self->warn("Perl module Text::Diff is not available");
+    return;
+  }
+
+  my @texts = map { ref $_ ? YAML::Dump($_) : $_ } ($item1, $item2);
+
+  $self->message($level, Text::Diff::diff(\$texts[0], \$texts[1], \%params));
+}
+
+sub _load_text_diff {
+  $text_diff_available = eval("use Text::Diff (); 1;") ? 1 : 0 unless defined $text_diff_available;
+  return $text_diff_available;
+}
+
 sub enable_sub_tracing {
   my ($self) = @_;
   $global_level |= TRACE;
@@ -225,7 +262,7 @@ sub _write {
   chomp($message);
 
   if ((FILE_TARGET == $self->{"target"})
-      && open(FILE, ">>" . $self->{"file"})) {
+      && open(FILE, ">>", $self->{"file"})) {
     print(FILE "${date}${message}\n");
     close(FILE);
 
@@ -255,9 +292,9 @@ 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);
+  $self->_write("time", $self->get_request_time() . (@slurp ? " (@slurp)" : ''));
 }
 
 sub get_request_time {
@@ -274,4 +311,293 @@ sub want_request_timer {
   $global_level & REQUEST_TIMER;
 }
 
+sub file {
+  @_ == 2 ? $_[0]->{file} = $_[1] : $_[0]->{file};
+}
+
+sub _by_name {
+  my ($self, $level) = @_;
+  my $meth = $self->can(uc $level);
+  die 'unknown level' unless $meth;
+  $meth->();
+}
+
+sub level_by_name {
+  my ($self, $level, $val) = @_;
+  if (@_ == 3) {
+    $global_level |=  $self->_by_name($level) if  $val;
+    $global_level &= ~$self->_by_name($level) if !$val;
+  }
+  return $global_level & $self->_by_name($level);
+}
+
 1;
+__END__
+
+=pod
+
+=encoding utf8
+
+=head1 NAME
+
+LXDebug - Lx-Office debugging facilities
+
+=head1 SYNOPSIS
+
+This module provides functions for debugging Lx-Office. An instance is
+always created as the global variable C<$::lxdebug> at the earliest
+possible moment.
+
+Debugging is mostly logging of information. Each log function has a
+I<level> and an I<object> to be logged. The configuration file as well
+as this module's functions determine which levels get logged, and
+which file they're logged to.
+
+=head1 LOG LEVELS
+
+The available log levels are:
+
+=over 4
+
+=item C<NONE>
+
+Always output the message regardless of the active levels. Only use
+this temporarily.
+
+=item C<INFO>
+
+Informational, not an error, more important than C<DEBUG1>.
+
+=item C<DEBUG1>
+
+Important debugging information.
+
+=item C<DEBUG2>
+
+Less important debugging information that occurs often and spams the
+log.
+
+=item C<QUERY>
+
+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,
+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>
+
+Log a stack trace when an error is output.
+
+=item C<REQUEST_TIMER>
+
+Log each request's total execution time when it finishes.
+
+=item C<WARN>
+
+Important warnings.
+
+=item C<ALL>
+
+All of the above.
+
+=item C<DEVEL>
+
+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/lx_office.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<show_debug_menu>
+
+A boolean (C<1> or C<0>). If turned on then certain debug facilities
+are available from the v1 menu. These include e.g.
+
+=over 6
+
+=item *
+
+restarting the FastCGI process by forcefully exiting after the
+request,
+
+=item *
+
+enabling and disabling function tracing,
+
+=item *
+
+enabling and disabling certain debug levels.
+
+=back
+
+Note that these are only useful if Lx-Office is running as a FastCGI
+application because otherwise the changes would be lost when the
+process exits in a normal CGI environment.
+
+=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
+
+=item C<enter_sub [$level]>
+
+=item C<leave_sub [$level]>
+
+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 the
+global log level C<TRACE2> is active as well.
+
+=item C<enable_sub_tracing>
+
+=item C<disable_sub_tracing>
+
+Enables/disables sub tracing with L<enter_sub>/L<leave_sub> temporarily.
+
+=item C<is_tracing_enabled>
+
+Returns whether or not the C<TRACE> debug level is active.
+
+=item C<show_backtrace [$force]>
+
+Logs a stack backtrace if C<$force> is trueish or if the log level
+C<BACKTRACE_ON_ERROR> is active.
+
+=item C<message $level, $message>
+
+Logs the message C<$message> if the log level C<$level> is active. The
+message will be prefixed with a word describing the log level.
+
+=item C<warn $message>
+
+Equivalent to C<message WARN(), $message>.
+
+=item C<dump $level, $name, $variable>
+
+Logs a message that the variable named C<$name> is dumped along with a
+dump of the variable C<$variable> created by the L<Data::Dumper>
+module. Will log a warning if said module is not available. Will only
+log if the log level C<$level> is active.
+
+=item C<dump_yaml $level, $name, $variable>
+
+Logs a message that the variable named C<$name> is dumped along with a
+dump of the variable C<$variable> created by the C<YAML> module. Will
+only log if the log level C<$level> is active.
+
+=item C<dump_sql $level, $prefix, $results>
+
+Dumps the result of an SQL query in tabular form. Will only log if the
+log level C<$level> is active.
+
+=item C<show_diff $level, $item1, $item2, %params>
+
+Logs a unified diff of the textual representations of C<$item1> and
+C<$item2>. Requires the module L<Text::Diff> and logs a warning if
+said module is not available.
+
+C<$item1> and C<$item2> are dumped via L<YAML::Dumper> before diffing
+if they're non-scalars.
+
+Will only log if the log level C<$level> is active.
+
+=item C<begin_request>
+
+=item C<end_request>
+
+=item C<log_time>
+
+=item C<set_request_timer>
+
+=item C<want_request_timer>
+
+Internal functions used to log the current request's exeuction time
+(log level C<REQUEST_TIMER>).
+
+=item C<get_request_time>
+
+Returns the current request's elapsed execution time in seconds.
+
+=item C<file [$file_name]>
+
+Sets and/or returns the file name this instance logs to.
+
+=item C<level_by_name $level[, $val]>
+
+Returns if a log level C<$level> is active. C<$level> is a string
+representation, not one of the level constants from above.
+
+If C<$val> is given then said level will be turned on (if C<$val> is
+trueish) or off (if C<$val> is falsish).
+
+=back
+
+=head1 BUGS
+
+Nothing here yet.
+
+=head1 AUTHOR
+
+Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>,
+Sven Schöling E<lt>s.schoeling@linet-services.deE<gt>
+
+=cut