3 use constant NONE => 0;
4 use constant INFO => 1;
5 use constant DEBUG1 => 1 << 1;
6 use constant DEBUG2 => 1 << 2;
7 use constant QUERY => 1 << 3;
8 use constant TRACE => 1 << 4;
9 use constant BACKTRACE_ON_ERROR => 1 << 5;
10 use constant REQUEST_TIMER => 1 << 6;
11 use constant REQUEST => 1 << 7;
12 use constant WARN => 1 << 8;
13 use constant TRACE2 => 1 << 9;
14 use constant SHOW_CALLER => 1 << 10;
15 use constant ALL => (1 << 11) - 1;
16 use constant DEVEL => INFO | DEBUG1 | QUERY | TRACE | BACKTRACE_ON_ERROR | REQUEST_TIMER;
18 use constant FILE_TARGET => 0;
19 use constant STDERR_TARGET => 1;
22 use POSIX qw(strftime getpid);
23 use Scalar::Util qw(blessed refaddr weaken);
24 use Time::HiRes qw(gettimeofday tv_interval);
31 my ($text_diff_available);
33 our $global_level = NONE();
41 _init_globals_from_config();
43 $self->{"calldepth"} = 0;
44 $self->{"file"} = $file_name || "/tmp/lx-office-debug.log";
45 $self->{"target"} = FILE_TARGET;
49 $self->{ $_[0] } = $_[1];
57 my $globals_inited_from_config;
58 sub _init_globals_from_config {
59 return if $globals_inited_from_config;
60 $globals_inited_from_config = 1;
62 my $cfg = $::lx_office_conf{debug} || {};
64 $global_level = NONE() if $cfg->{global_level} =~ /NONE/;
65 foreach my $level (grep { $_} split(m/\s+/, $cfg->{global_level})) {
66 $global_level |= eval "${level}()";
69 $watch_form = $cfg->{watch_form};
70 $file_name = $cfg->{file_name} || "/tmp/lx-office-debug.log";
74 my ($self, $target, $file) = @_;
76 if ((FILE_TARGET == $target) && $file) {
77 $self->{"file"} = $file;
78 $self->{"target"} = FILE_TARGET;
80 } elsif (STDERR_TARGET == $target) {
81 $self->{"target"} = STDERR_TARGET;
87 my $level = shift || 0;
89 return 1 unless ($global_level & TRACE); # ignore if traces aren't active
90 return 1 if $level && !($global_level & TRACE2); # ignore if level of trace isn't active
92 my ($package, $filename, $line, $subroutine) = caller(1);
93 my ($dummy1, $self_filename, $self_line) = caller(0);
95 my $indent = " " x $self->{"calldepth"}++;
96 my $time = $self->get_request_time || '';
98 if (!defined($package)) {
99 $self->_write('sub' . $level, $indent . "\\ $time top-level?\n");
101 $self->_write('sub' . $level, $indent
102 . "\\ $time ${subroutine} in "
103 . "${self_filename}:${self_line} called from "
104 . "${filename}:${line}\n");
111 my $level = shift || 0;
113 return 1 unless ($global_level & TRACE); # ignore if traces aren't active
114 return 1 if $level && !($global_level & TRACE2); # ignore if level of trace isn't active
116 my ($package, $filename, $line, $subroutine) = caller(1);
117 my ($dummy1, $self_filename, $self_line) = caller(0);
119 my $indent = " " x --$self->{"calldepth"};
120 my $time = $self->want_request_timer ? $self->get_request_time || '' : '';
122 if (!defined($package)) {
123 $self->_write('sub' . $level, $indent . "/ $time top-level?\n");
125 $self->_write('sub' . $level, $indent . "/ $time ${subroutine} in " . "${self_filename}:${self_line}\n");
131 my ($self, $force) = @_;
133 return 1 unless ($force || ($global_level & BACKTRACE_ON_ERROR));
135 $self->message(0, "Starting full caller dump:");
137 while (my ($dummy, $filename, $line, $subroutine) = caller $level) {
138 $self->message(0, " ${subroutine} from ${filename}:${line}");
147 my ($self, $level, $message) = @_;
149 my $show_caller = ($level | $global_level) & SHOW_CALLER();
150 $level &= ~SHOW_CALLER();
152 $self->_write(level2string($level), $message, show_caller => $show_caller) if (($self->{"level"} | $global_level) & $level || !$level);
156 my ($self, $message) = @_;
157 $self->message(WARN, $message);
161 my ($src, $dumped) = @_;
163 return undef if !defined($src);
164 return $src if !ref($src);
167 my $addr = refaddr($src);
169 return $dumped->{$addr} if $dumped->{$addr // ''};
172 if (blessed($src) && $src->can('as_debug_info')) {
173 $dumped->{$addr} = $src->as_debug_info;
175 } elsif (ref($src) eq 'ARRAY') {
176 $dumped->{$addr} = [];
178 foreach my $entry (@{ $src }) {
179 my $exists = !!$dumped->{refaddr($entry) // ''};
180 push @{ $dumped->{$addr} }, clone_for_dump($entry, $dumped);
182 weaken($dumped->{$addr}->[-1]) if $exists;
186 } elsif (ref($src) =~ m{^(?:HASH|Form|SL::.+)$}) {
187 $dumped->{$addr} = {};
189 foreach my $key (keys %{ $src }) {
190 my $exists = !!$dumped->{refaddr($src->{$key}) // ''};
191 $dumped->{$addr}->{$key} = clone_for_dump($src->{$key}, $dumped);
193 weaken($dumped->{$addr}->{$key}) if $exists;
197 return $dumped->{$addr} // "$src";
201 my ($self, $level, $name, $variable, %options) = @_;
203 $variable = clone_for_dump($variable);
204 my $dumper = Data::Dumper->new([$variable]);
205 $dumper->Sortkeys(1);
207 $dumper->$_($options{$_}) for keys %options;
208 my $output = $dumper->Dump();
209 $self->message($level, "dumping ${name}:\n" . $output);
215 my ($self, $level, $name, $variable) = @_;
217 $self->message($level, "dumping ${name}:\n" . SL::YAML::Dump($variable));
220 sub dump_sql_result {
221 my ($self, $level, $prefix, $results) = @_;
223 if (!$results || !scalar @{ $results }) {
224 $self->message($level, "Empty result set");
228 my %column_lengths = map { $_, length $_ } keys %{ $results->[0] };
230 foreach my $row (@{ $results }) {
231 map { $column_lengths{$_} = length $row->{$_} if (length $row->{$_} > $column_lengths{$_}) } keys %{ $row };
234 my @sorted_names = sort keys %column_lengths;
235 my $format = join '|', map { '%' . $column_lengths{$_} . 's' } @sorted_names;
237 $prefix .= ' ' if $prefix;
239 $self->message($level, $prefix . sprintf($format, @sorted_names));
240 $self->message($level, $prefix . join('+', map { '-' x $column_lengths{$_} } @sorted_names));
242 foreach my $row (@{ $results }) {
243 $self->message($level, $prefix . sprintf($format, map { $row->{$_} } @sorted_names));
245 $self->message($level, $prefix . sprintf('(%d row%s)', scalar @{ $results }, scalar @{ $results } > 1 ? 's' : ''));
249 my ($self, $level, $item1, $item2, %params) = @_;
251 if (!$self->_load_text_diff) {
252 $self->warn("Perl module Text::Diff is not available");
256 my @texts = map { ref $_ ? SL::YAML::Dump($_) : $_ } ($item1, $item2);
258 $self->message($level, Text::Diff::diff(\$texts[0], \$texts[1], \%params));
261 sub _load_text_diff {
262 $text_diff_available = eval("use Text::Diff (); 1;") ? 1 : 0 unless defined $text_diff_available;
263 return $text_diff_available;
266 sub enable_sub_tracing {
268 $global_level |= TRACE;
271 sub disable_sub_tracing {
273 $global_level &= ~ TRACE;
276 sub is_tracing_enabled {
278 return $global_level & TRACE;
283 my ($self, $prefix, $message, %options) = @_;
285 my @prefixes = ($prefix);
287 if ($options{show_caller}) {
290 my ($package, $filename, $line, $subroutine) = caller($level);
292 if (($filename // '') =~ m{LXDebug\.pm$}) {
297 push @prefixes, "${filename}:${line}";
302 $prefix = join ' ', grep { $_ } @prefixes;
304 my @now = gettimeofday();
305 my $date = strftime("%Y-%m-%d %H:%M:%S." . sprintf('%03d', int($now[1] / 1000)) . " $$ [" . getpid() . "] ${prefix}: ", localtime($now[0]));
309 $self->_write_raw("${date}${message}\n");
313 my ($self, $message) = @_;
315 if ((FILE_TARGET == $self->{"target"})
316 && open(FILE, ">>", $self->{"file"})) {
317 binmode FILE, ":utf8";
321 } elsif (STDERR_TARGET == $self->{"target"}) {
322 print STDERR $message;
328 # use $_[0] as a bit mask and return levelstrings separated by /
329 join '/', qw(info debug1 debug2 query trace error_call_trace request_timer request WARNING trace2 show_caller)[ grep { (reverse split //, sprintf "%011b", $_[0])[$_] } 0..11 ]
334 return 1 unless want_request_timer();
335 $self->set_request_timer;
339 my ($self, %params) = @_;
340 return 1 unless want_request_timer();
342 $self->_write("time", sprintf('%f (%s/%s)', $self->get_request_time, $params{script_name}, $params{action}));
344 $self->{calldepth} = 0;
348 my ($self, @slurp) = @_;
349 return 1 unless want_request_timer();
351 my $now = $self->get_request_time;
353 return 1 unless $now;
355 my $diff = $self->{previous_log_time} ? int((($now - ($self->{previous_log_time} // 0)) * 10_000 + 5) / 10) : $now * 10_0000 + 5;
356 $self->{previous_log_time} = $now;
358 $self->_write("time", "${now}s Δ ${diff}ms" . (@slurp ? " (@slurp)" : ''));
361 sub get_request_time {
363 return $self->want_request_timer && $self->{request_start} ? tv_interval($self->{request_start}) : undef;
366 sub set_request_timer {
368 $self->{request_start} = [gettimeofday];
371 sub want_request_timer {
372 $global_level & REQUEST_TIMER;
376 @_ == 2 ? $_[0]->{file} = $_[1] : $_[0]->{file};
380 my ($self, $level) = @_;
381 my $meth = $self->can(uc $level);
382 die 'unknown level' unless $meth;
387 my ($self, $level, $val) = @_;
389 $global_level |= $self->_by_name($level) if $val;
390 $global_level &= ~$self->_by_name($level) if !$val;
392 return $global_level & $self->_by_name($level);
395 sub is_request_logging_enabled {
397 return $global_level & REQUEST;
400 sub add_request_params {
401 my ($self, $key, $value) = @_;
402 return unless $self->is_request_logging_enabled;
403 return if $key =~ /password/;
405 push @{ $::request->{debug}{PARAMS} ||= [] }, [ $key => $value ];
409 my ($self, $type, $controller, $action) = @_;
410 return unless $self->is_request_logging_enabled;
412 my $session_id = $::auth->create_or_refresh_session;
414 my $template = <<EOL;
415 *************************************
416 $ENV{REQUEST_METHOD} $ENV{SCRIPT_NAME} $session_id ($::myconfig{login})
417 routing: $type, controller: $controller, action: $action
420 $self->_write('Request', $template);
422 my $params = join "\n ", map {
424 } @{ $::request->{debug}{PARAMS} || [] };
426 $self->_write_raw(<<EOL);
442 LXDebug - kivitendo debugging facilities
446 This module provides functions for debugging kivitendo. An instance is
447 always created as the global variable C<$::lxdebug> at the earliest
450 Debugging is mostly logging of information. Each log function has a
451 I<level> and an I<object> to be logged. The configuration file as well
452 as this module's functions determine which levels get logged, and
453 which file they're logged to.
457 The available log levels are:
463 Always output the message regardless of the active levels. Only use
468 Informational, not an error, more important than C<DEBUG1>.
472 Important debugging information.
476 Less important debugging information that occurs often and spams the
481 Log all queries executed by the L<SL::DBUtils> utility methods.
485 Log sub calls and exits via the L<enter_sub>/L<leave_sub> functions,
486 but only if they're called with a log level that is falsish
487 (e.g. none, C<undef>, 0).
491 Log sub calls and exits via the L<enter_sub>/L<leave_sub> functions
492 even if they're called with a log level of 2. Will only have an effect
493 if C<TRACE> is set as well.
495 =item C<BACKTRACE_ON_ERROR>
497 Log a stack trace when an error is output.
499 =item C<REQUEST_TIMER>
501 Log each request's total execution time when it finishes.
513 Shortcut for C<INFO | QUERY | TRACE | BACKTRACE_ON_ERROR | REQUEST_TIMER>.
519 C<SL::LXDebug> gets its configuration from the C<[debug]> section of
520 the C<config/kivitendo.conf> configuration file. The available options
525 =item C<global_level>
527 A string of log level names that should be activated by
528 default. Multiple log levels are separated by C<|>.
532 A boolean (C<1> or C<0>). Turns on the C<$::form> watch facility. If
533 this is enabled then any key inside C<$::form> can be monitored for
534 changes. For example:
536 # Start watching 'action'
537 $::form->{"Watchdog::action"} = 1;
538 # Stop watching 'invtotal'
539 $::form->{"Watchdog::invtotal"} = 0;
541 A log message is written when the watchdog is enabled for a variable
542 and for each subsequent change. The log message includes the place
543 (file name and line number) of the instruction changing the key.
545 Note that this entails a performance penalty. Also only the keys
546 themselves are monitored -- not the references they point to. E.g. the
547 following would not trigger a change:
549 $::form->{"Watchdog::some_hash"} = 1;
551 $::form->{some_hash}->{some_value} = 42;
553 $::form->{some_hash} = { something => 'else' };
555 =item C<keep_temp_files>
557 A boolean (C<1> or C<0>). If turned on then certain temporary files
558 are not removed but kept in the C<users> directory. These include the
559 temporary files used during printing, e.g. LaTeX files.
563 The path and file name of the debug log file. Must be a location
564 writeable by the web server process.
572 =item C<enter_sub [$level]>
574 =item C<leave_sub [$level]>
576 Pairs of these can be put near the beginning/end of a sub. They'll
577 cause a trace to be written to the log file if the C<TRACE> level is
580 If C<$level> is given then the log messages will only be logged if the
581 global log level C<TRACE2> is active as well.
583 =item C<enable_sub_tracing>
585 =item C<disable_sub_tracing>
587 Enables/disables sub tracing with L<enter_sub>/L<leave_sub> temporarily.
589 =item C<is_tracing_enabled>
591 Returns whether or not the C<TRACE> debug level is active.
593 =item C<show_backtrace [$force]>
595 Logs a stack backtrace if C<$force> is trueish or if the log level
596 C<BACKTRACE_ON_ERROR> is active.
598 =item C<message $level, $message>
600 Logs the message C<$message> if the log level C<$level> is active. The
601 message will be prefixed with a word describing the log level.
603 =item C<warn $message>
605 Equivalent to C<message WARN(), $message>.
607 =item C<dump $level, $name, $variable>
609 Logs a message that the variable named C<$name> is dumped along with a
610 dump of the variable C<$variable> created by the L<Data::Dumper>
611 module. Will log a warning if said module is not available. Will only
612 log if the log level C<$level> is active.
614 =item C<dump_yaml $level, $name, $variable>
616 Logs a message that the variable named C<$name> is dumped along with a
617 dump of the variable C<$variable> created by the C<YAML> module. Will
618 only log if the log level C<$level> is active.
620 =item C<dump_sql $level, $prefix, $results>
622 Dumps the result of an SQL query in tabular form. Will only log if the
623 log level C<$level> is active.
625 =item C<show_diff $level, $item1, $item2, %params>
627 Logs a unified diff of the textual representations of C<$item1> and
628 C<$item2>. Requires the module L<Text::Diff> and logs a warning if
629 said module is not available.
631 C<$item1> and C<$item2> are dumped via L<YAML::Dumper> before diffing
632 if they're non-scalars.
634 Will only log if the log level C<$level> is active.
636 =item C<begin_request>
642 =item C<set_request_timer>
644 =item C<want_request_timer>
646 Internal functions used to log the current request's exeuction time
647 (log level C<REQUEST_TIMER>).
649 =item C<get_request_time>
651 Returns the current request's elapsed execution time in seconds.
653 =item C<file [$file_name]>
655 Sets and/or returns the file name this instance logs to.
657 =item C<level_by_name $level[, $val]>
659 Returns if a log level C<$level> is active. C<$level> is a string
660 representation, not one of the level constants from above.
662 If C<$val> is given then said level will be turned on (if C<$val> is
663 trueish) or off (if C<$val> is falsish).
673 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>,
674 Sven Schöling E<lt>s.schoeling@linet-services.deE<gt>