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 WARN => 1 << 7;
12 use constant TRACE2 => 1 << 8;
13 use constant ALL => (1 << 9) - 1;
14 use constant DEVEL => INFO | DEBUG1 | QUERY | TRACE | BACKTRACE_ON_ERROR | REQUEST_TIMER;
16 use constant FILE_TARGET => 0;
17 use constant STDERR_TARGET => 1;
19 use POSIX qw(strftime getppid);
20 use Time::HiRes qw(gettimeofday tv_interval);
25 my ($data_dumper_available, $text_diff_available);
32 eval("use Data::Dumper");
33 $data_dumper_available = $@ ? 0 : 1;
43 _init_globals_from_config();
45 $self->{"calldepth"} = 0;
46 $self->{"file"} = $file_name || "/tmp/lx-office-debug.log";
47 $self->{"target"} = FILE_TARGET;
51 $self->{ $_[0] } = $_[1];
59 my $globals_inited_from_config;
60 sub _init_globals_from_config {
61 return if $globals_inited_from_config;
62 $globals_inited_from_config = 1;
64 my $cfg = $::lx_office_conf{debug} || {};
66 $global_level = NONE() if $cfg->{global_level} =~ /NONE/;
67 foreach my $level (grep { $_} split(m/\s+/, $cfg->{global_level})) {
68 $global_level |= eval "${level}()";
71 $watch_form = $cfg->{watch_form};
72 $file_name = $cfg->{file_name} || "/tmp/lx-office-debug.log";
76 my ($self, $target, $file) = @_;
78 if ((FILE_TARGET == $target) && $file) {
79 $self->{"file"} = $file;
80 $self->{"target"} = FILE_TARGET;
82 } elsif (STDERR_TARGET == $target) {
83 $self->{"target"} = STDERR_TARGET;
89 my $level = shift || 0;
91 return 1 unless ($global_level & TRACE); # ignore if traces aren't active
92 return 1 if $level && !($global_level & TRACE2); # ignore if level of trace isn't active
94 my ($package, $filename, $line, $subroutine) = caller(1);
95 my ($dummy1, $self_filename, $self_line) = caller(0);
97 my $indent = " " x $self->{"calldepth"}++;
98 my $time = $self->get_request_time || '';
100 if (!defined($package)) {
101 $self->_write('sub' . $level, $indent . "\\ $time top-level?\n");
103 $self->_write('sub' . $level, $indent
104 . "\\ $time ${subroutine} in "
105 . "${self_filename}:${self_line} called from "
106 . "${filename}:${line}\n");
113 my $level = shift || 0;
115 return 1 unless ($global_level & TRACE); # ignore if traces aren't active
116 return 1 if $level && !($global_level & TRACE2); # ignore if level of trace isn't active
118 my ($package, $filename, $line, $subroutine) = caller(1);
119 my ($dummy1, $self_filename, $self_line) = caller(0);
121 my $indent = " " x --$self->{"calldepth"};
122 my $time = $self->want_request_timer ? $self->get_request_time || '' : '';
124 if (!defined($package)) {
125 $self->_write('sub' . $level, $indent . "/ $time top-level?\n");
127 $self->_write('sub' . $level, $indent . "/ $time ${subroutine} in " . "${self_filename}:${self_line}\n");
133 my ($self, $force) = @_;
135 return 1 unless ($force || ($global_level & BACKTRACE_ON_ERROR));
137 $self->message(BACKTRACE_ON_ERROR, "Starting full caller dump:");
139 while (my ($dummy, $filename, $line, $subroutine) = caller $level) {
140 $self->message(BACKTRACE_ON_ERROR, " ${subroutine} from ${filename}:${line}");
149 my ($self, $level, $message) = @_;
151 $self->_write(level2string($level), $message) if (($self->{"level"} | $global_level) & $level || !$level);
155 my ($self, $message) = @_;
156 $self->message(WARN, $message);
160 my ($self, $level, $name, $variable, %options) = @_;
162 if ($data_dumper_available) {
164 if ($variable && ('Form' eq ref $variable) && defined $variable->{password}) {
165 $password = $variable->{password};
166 $variable->{password} = 'X' x 8;
169 my $dumper = Data::Dumper->new([$variable]);
170 $dumper->Sortkeys(1);
172 $dumper->$_($options{$_}) for keys %options;
173 $self->message($level, "dumping ${name}:\n" . $dumper->Dump());
175 $variable->{password} = $password if (defined $password);
177 # Data::Dumper does not reset the iterator belonging to this hash
178 # if 'Sortkeys' is true. Therefore clear the iterator manually.
179 # See "perldoc -f each".
180 if ($variable && (('HASH' eq ref $variable) || ('Form' eq ref $variable))) {
185 $self->message($level,
186 "dumping ${name}: Data::Dumper not available; "
187 . "variable cannot be dumped");
192 my ($self, $level, $name, $variable) = @_;
194 $self->message($level, "dumping ${name}:\n" . YAML::Dump($variable));
197 sub dump_sql_result {
198 my ($self, $level, $prefix, $results) = @_;
200 if (!$results || !scalar @{ $results }) {
201 $self->message($level, "Empty result set");
205 my %column_lengths = map { $_, length $_ } keys %{ $results->[0] };
207 foreach my $row (@{ $results }) {
208 map { $column_lengths{$_} = length $row->{$_} if (length $row->{$_} > $column_lengths{$_}) } keys %{ $row };
211 my @sorted_names = sort keys %column_lengths;
212 my $format = join '|', map { '%' . $column_lengths{$_} . 's' } @sorted_names;
214 $prefix .= ' ' if $prefix;
216 $self->message($level, $prefix . sprintf($format, @sorted_names));
217 $self->message($level, $prefix . join('+', map { '-' x $column_lengths{$_} } @sorted_names));
219 foreach my $row (@{ $results }) {
220 $self->message($level, $prefix . sprintf($format, map { $row->{$_} } @sorted_names));
222 $self->message($level, $prefix . sprintf('(%d row%s)', scalar @{ $results }, scalar @{ $results } > 1 ? 's' : ''));
226 my ($self, $level, $item1, $item2, %params) = @_;
228 if (!$self->_load_text_diff) {
229 $self->warn("Perl module Text::Diff is not available");
233 my @texts = map { ref $_ ? YAML::Dump($_) : $_ } ($item1, $item2);
235 $self->message($level, Text::Diff::diff(\$texts[0], \$texts[1], \%params));
238 sub _load_text_diff {
239 $text_diff_available = eval("use Text::Diff (); 1;") ? 1 : 0 unless defined $text_diff_available;
240 return $text_diff_available;
243 sub enable_sub_tracing {
245 $global_level |= TRACE;
248 sub disable_sub_tracing {
250 $global_level &= ~ TRACE;
253 sub is_tracing_enabled {
255 return $global_level & TRACE;
260 my ($self, $prefix, $message) = @_;
261 my $date = strftime("%Y-%m-%d %H:%M:%S $$ [" . getppid() . "] ${prefix}: ", localtime(time()));
266 if ((FILE_TARGET == $self->{"target"})
267 && open(FILE, ">>", $self->{"file"})) {
268 print(FILE "${date}${message}\n");
271 } elsif (STDERR_TARGET == $self->{"target"}) {
272 print(STDERR "${date}${message}\n");
278 # use $_[0] as a bit mask and return levelstrings separated by /
279 join '/', qw(info debug1 debug2 query trace error_call_trace request_timer WARNING)[ grep { (reverse split //, sprintf "%08b", $_[0])[$_] } 0..7 ]
284 return 1 unless want_request_timer();
285 $self->set_request_timer;
290 return 1 unless want_request_timer();
291 $self->_write("time", $self->get_request_time);
293 $self->{calldepth} = 0;
297 my ($self, @slurp) = @_;
298 return 1 unless want_request_timer();
299 $self->_write("time", $self->get_request_time() . (@slurp ? " (@slurp)" : ''));
302 sub get_request_time {
304 return $self->want_request_timer && $self->{request_start} ? tv_interval($self->{request_start}) : undef;
307 sub set_request_timer {
309 $self->{request_start} = [gettimeofday];
312 sub want_request_timer {
313 $global_level & REQUEST_TIMER;
317 @_ == 2 ? $_[0]->{file} = $_[1] : $_[0]->{file};
321 my ($self, $level) = @_;
322 my $meth = $self->can(uc $level);
323 die 'unknown level' unless $meth;
328 my ($self, $level, $val) = @_;
330 $global_level |= $self->_by_name($level) if $val;
331 $global_level &= ~$self->_by_name($level) if !$val;
333 return $global_level & $self->_by_name($level);
345 LXDebug - kivitendo debugging facilities
349 This module provides functions for debugging kivitendo. An instance is
350 always created as the global variable C<$::lxdebug> at the earliest
353 Debugging is mostly logging of information. Each log function has a
354 I<level> and an I<object> to be logged. The configuration file as well
355 as this module's functions determine which levels get logged, and
356 which file they're logged to.
360 The available log levels are:
366 Always output the message regardless of the active levels. Only use
371 Informational, not an error, more important than C<DEBUG1>.
375 Important debugging information.
379 Less important debugging information that occurs often and spams the
384 Log all queries executed by the L<SL::DBUtils> utility methods.
388 Log sub calls and exits via the L<enter_sub>/L<leave_sub> functions,
389 but only if they're called with a log level that is falsish
390 (e.g. none, C<undef>, 0).
394 Log sub calls and exits via the L<enter_sub>/L<leave_sub> functions
395 even if they're called with a log level of 2. Will only have an effect
396 if C<TRACE> is set as well.
398 =item C<BACKTRACE_ON_ERROR>
400 Log a stack trace when an error is output.
402 =item C<REQUEST_TIMER>
404 Log each request's total execution time when it finishes.
416 Shortcut for C<INFO | QUERY | TRACE | BACKTRACE_ON_ERROR | REQUEST_TIMER>.
422 C<SL::LXDebug> gets its configuration from the C<[debug]> section of
423 the C<config/kivitendo.conf> configuration file. The available options
428 =item C<global_level>
430 A string of log level names that should be activated by
431 default. Multiple log levels are separated by C<|>.
435 A boolean (C<1> or C<0>). Turns on the C<$::form> watch facility. If
436 this is enabled then any key inside C<$::form> can be monitored for
437 changes. For example:
439 # Start watching 'action'
440 $::form->{"Watchdog::action"} = 1;
441 # Stop watching 'invtotal'
442 $::form->{"Watchdog::invtotal"} = 0;
444 A log message is written when the watchdog is enabled for a variable
445 and for each subsequent change. The log message includes the place
446 (file name and line number) of the instruction changing the key.
448 Note that this entails a performance penalty. Also only the keys
449 themselves are monitored -- not the references they point to. E.g. the
450 following would not trigger a change:
452 $::form->{"Watchdog::some_hash"} = 1;
454 $::form->{some_hash}->{some_value} = 42;
456 $::form->{some_hash} = { something => 'else' };
458 =item C<keep_temp_files>
460 A boolean (C<1> or C<0>). If turned on then certain temporary files
461 are not removed but kept in the C<users> directory. These include the
462 temporary files used during printing, e.g. LaTeX files.
466 The path and file name of the debug log file. Must be a location
467 writeable by the web server process.
475 =item C<enter_sub [$level]>
477 =item C<leave_sub [$level]>
479 Pairs of these can be put near the beginning/end of a sub. They'll
480 cause a trace to be written to the log file if the C<TRACE> level is
483 If C<$level> is given then the log messages will only be logged if the
484 global log level C<TRACE2> is active as well.
486 =item C<enable_sub_tracing>
488 =item C<disable_sub_tracing>
490 Enables/disables sub tracing with L<enter_sub>/L<leave_sub> temporarily.
492 =item C<is_tracing_enabled>
494 Returns whether or not the C<TRACE> debug level is active.
496 =item C<show_backtrace [$force]>
498 Logs a stack backtrace if C<$force> is trueish or if the log level
499 C<BACKTRACE_ON_ERROR> is active.
501 =item C<message $level, $message>
503 Logs the message C<$message> if the log level C<$level> is active. The
504 message will be prefixed with a word describing the log level.
506 =item C<warn $message>
508 Equivalent to C<message WARN(), $message>.
510 =item C<dump $level, $name, $variable>
512 Logs a message that the variable named C<$name> is dumped along with a
513 dump of the variable C<$variable> created by the L<Data::Dumper>
514 module. Will log a warning if said module is not available. Will only
515 log if the log level C<$level> is active.
517 =item C<dump_yaml $level, $name, $variable>
519 Logs a message that the variable named C<$name> is dumped along with a
520 dump of the variable C<$variable> created by the C<YAML> module. Will
521 only log if the log level C<$level> is active.
523 =item C<dump_sql $level, $prefix, $results>
525 Dumps the result of an SQL query in tabular form. Will only log if the
526 log level C<$level> is active.
528 =item C<show_diff $level, $item1, $item2, %params>
530 Logs a unified diff of the textual representations of C<$item1> and
531 C<$item2>. Requires the module L<Text::Diff> and logs a warning if
532 said module is not available.
534 C<$item1> and C<$item2> are dumped via L<YAML::Dumper> before diffing
535 if they're non-scalars.
537 Will only log if the log level C<$level> is active.
539 =item C<begin_request>
545 =item C<set_request_timer>
547 =item C<want_request_timer>
549 Internal functions used to log the current request's exeuction time
550 (log level C<REQUEST_TIMER>).
552 =item C<get_request_time>
554 Returns the current request's elapsed execution time in seconds.
556 =item C<file [$file_name]>
558 Sets and/or returns the file name this instance logs to.
560 =item C<level_by_name $level[, $val]>
562 Returns if a log level C<$level> is active. C<$level> is a string
563 representation, not one of the level constants from above.
565 If C<$val> is given then said level will be turned on (if C<$val> is
566 trueish) or off (if C<$val> is falsish).
576 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>,
577 Sven Schöling E<lt>s.schoeling@linet-services.deE<gt>