4 use base qw( FS::Record );
5 use FS::Record qw( qsearch qsearchs dbdef );
6 use FS::UID qw( dbh driver_name );
9 use FS::upgrade_journal;
13 FS::log - Object methods for log records
19 $record = new FS::log \%hash;
20 $record = new FS::log { 'column' => 'value' };
22 $error = $record->insert;
24 $error = $new_record->replace($old_record);
26 $error = $record->delete;
28 $error = $record->check;
32 An FS::log object represents a log entry. FS::log inherits from
33 FS::Record. The following fields are currently supported:
37 =item lognum - primary key
39 =item _date - Unix timestamp
41 =item agentnum - L<FS::agent> to which the log pertains. If it involves a
42 specific customer, package, service, invoice, or other agent-specific object,
43 this will be set to that agentnum.
45 =item tablename - table name to which the log pertains, if any.
47 =item tablenum - foreign key to that table.
49 =item level - log level: 'debug', 'info', 'notice', 'warning', 'error',
50 'critical', 'alert', 'emergency'.
52 =item message - contents of the log entry
62 Creates a new log entry. Use FS::Log instead of calling this directly,
69 =item insert [ CONTEXT... ]
71 Adds this record to the database. If there is an error, returns the error,
72 otherwise returns false.
74 CONTEXT may be a list of context tags to attach to this record.
76 Will send emails according to the conditions in L<FS::log_email>.
81 # not using process_o2m for this, because we don't have a web interface
83 my $error = $self->SUPER::insert;
84 return $error if $error;
85 my $contexts = {}; #for quick checks when sending emails
87 my $context = FS::log_context->new({
88 'lognum' => $self->lognum,
91 $error = $context->insert;
92 return $error if $error;
95 foreach my $log_email (
101 'value' => $self->level,
106 # shouldn't be a lot of these, so not packing this into the qsearch
107 next if $log_email->context && !$contexts->{$log_email->context};
108 my $msg_template = qsearchs('msg_template',{ 'msgnum' => $log_email->msgnum });
109 unless ($msg_template) {
110 warn "Could not send email when logging, could not load message template for logemailnum " . $log_email->logemailnum;
113 my $emailerror = $msg_template->send(
114 'msgtype' => 'admin',
115 'to' => $log_email->to_addr,
117 'loglevel' => $FS::Log::LEVELS[$self->level], # which has hopefully been loaded...
118 'logcontext' => $log_email->context, # use the one that triggered the email
119 'logmessage' => $self->message,
122 warn "Could not send email when logging: $emailerror" if $emailerror;
127 # these methods can be inherited from FS::Record
129 sub delete { die "Log entries can't be modified." };
131 sub replace { die "Log entries can't be modified." };
135 Checks all fields to make sure this is a valid example. If there is
136 an error, returns the error, otherwise returns false. Called by the insert
145 $self->ut_numbern('lognum')
146 || $self->ut_number('_date')
147 || $self->ut_numbern('agentnum')
148 || $self->ut_foreign_keyn('agentnum', 'agent', 'agentnum')
149 || $self->ut_textn('tablename')
150 || $self->ut_numbern('tablenum')
151 || $self->ut_number('level')
152 || $self->ut_anything('message')
154 return $error if $error;
156 if ( my $tablename = $self->tablename ) {
157 my $dbdef_table = dbdef->table($tablename)
158 or return "tablename '$tablename' does not exist";
159 $error = $self->ut_foreign_key('tablenum',
161 $dbdef_table->primary_key);
162 return $error if $error;
170 Returns the context for this log entry, as an array, from least to most
177 map { $_->context } qsearch({
178 table => 'log_context',
179 hashref => { lognum => $self->lognum },
180 order_by => 'ORDER BY logcontextnum ASC',
192 Returns a qsearch hash expression to search for parameters specified in
193 HASHREF. Valid parameters are:
199 =item date - arrayref of start and end date
201 =item level - either a specific level, or an arrayref of min and max level
203 =item context - a context string that the log entry must have. This may
204 change in the future to allow searching for combinations of context strings.
206 =item object - any database object, to find log entries related to it.
208 =item tablename, tablenum - alternate way of specifying 'object'.
210 =item custnum - a customer number, to find log entries related to the customer
211 or any of their subordinate objects (invoices, packages, etc.).
213 =item message - a text string to search in messages. The search will be
214 a case-insensitive LIKE with % appended at both ends.
220 # used for custnum search: all tables with custnums
223 sub _setup_table_stubs {
249 my $pkey = dbdef->table($table)->primary_key;
251 "log.tablename = '$table' AND ".
252 "EXISTS(SELECT 1 FROM $table WHERE log.tablenum = $table.$pkey AND ".
253 "$table.custnum = "; # needs a closing )
257 "(log.tablename LIKE 'svc_%' OR log.tablename = 'cust_svc') AND ".
258 "EXISTS(SELECT 1 FROM cust_svc JOIN cust_pkg USING (svcnum) WHERE ".
259 "cust_pkg.custnum = "; # needs a closing )
263 my ($class, $params) = @_;
270 if ( $params->{'agentnum'} =~ /^(\d+)$/ ) {
279 if ( $params->{'custnum'} =~ /^(\d+)$/ ) {
280 _setup_table_stubs() unless @table_stubs;
282 my @orwhere = map { "( $_ $custnum) )" } @table_stubs;
283 push @where, join(' OR ', @orwhere);
290 if ( ref $params->{'level'} eq 'ARRAY' ) {
291 my ($min, $max) = @{ $params->{'level'} };
292 if ( $min =~ /^\d+$/ ) {
293 push @where, "log.level >= $min";
295 if ( $max =~ /^\d+$/ ) {
296 push @where, "log.level <= $max";
298 } elsif ( $params->{'level'} =~ /^(\d+)$/ ) {
299 push @where, "log.level = $1";
306 if ( ref $params->{'date'} eq 'ARRAY' ) {
307 my ($beg, $end) = @{ $params->{'date'} };
308 if ( $beg =~ /^\d+$/ ) {
309 push @where, "log._date >= $beg";
311 if ( $end =~ /^\d+$/ ) {
312 push @where, "log._date <= $end";
320 if ( $params->{'object'} and $params->{'object'}->isa('FS::Record') ) {
321 my $table = $params->{'object'}->table;
322 my $pkey = dbdef->table($table)->primary_key;
323 my $tablenum = $params->{'object'}->get($pkey);
324 if ( $table and $tablenum ) {
325 push @where, "log.tablename = '$table'", "log.tablenum = $tablenum";
327 } elsif ( $params->{'tablename'} =~ /^(\w+)$/ ) {
329 if ( $params->{'tablenum'} =~ /^(\d+)$/ ) {
330 push @where, "log.tablename = '$table'", "log.tablenum = $1";
338 if ( $params->{'message'} ) { # can be anything, really, so escape it
339 my $quoted_message = dbh->quote('%' . $params->{'message'} . '%');
340 my $op = (driver_name eq 'Pg' ? 'ILIKE' : 'LIKE');
341 push @where, "log.message $op $quoted_message";
348 if ( $params->{'context'} ) {
349 my $quoted = dbh->quote($params->{'context'});
350 if ( $params->{'context_height'} =~ /^\d+$/ ) {
351 my $subq = 'SELECT context FROM log_context WHERE log.lognum = log_context.lognum'.
352 ' ORDER BY logcontextnum DESC LIMIT '.$params->{'context_height'};
354 "EXISTS(SELECT 1 FROM ($subq) AS log_context_x WHERE log_context_x.context = $quoted)";
357 "EXISTS(SELECT 1 FROM log_context WHERE log.lognum = log_context.lognum ".
358 "AND log_context.context = $quoted)";
362 # agent virtualization
363 my $access_user = $FS::CurrentUser::CurrentUser;
364 push @where, $access_user->agentnums_sql(
366 viewall_right => 'Configuration',
372 $extra_sql .= 'WHERE ' . join(' AND ', @where) if @where;
373 my $count_query = 'SELECT COUNT(*) FROM log '.$extra_sql;
378 'extra_sql' => $extra_sql,
379 'count_query' => $count_query,
380 'order_by' => 'ORDER BY _date ASC',
381 #addl_from, not needed
386 my ($class, %opts) = @_;
388 return if FS::upgrade_journal->is_done('log__remap_levels');
390 tie my %levelmap, 'Tie::IxHash',
393 2 => 1, #notice -> info
397 6 => 4, #alert -> critical
398 7 => 4, #emergency -> critical
401 # this method should never autocommit
402 # should have been set in upgrade, but just in case...
403 local $FS::UID::AutoCommit = 0;
405 # FS::log has no replace method
406 # in practice, only debug/info/warning/error were used,
407 # so this should only hit warning/error
408 foreach my $old (keys %levelmap) {
409 my $sql = 'UPDATE log SET level=' . dbh->quote($levelmap{$old}) . ' WHERE level=' . dbh->quote($old);
410 warn $sql unless $opts{'quiet'};
411 my $sth = dbh->prepare($sql) or die dbh->errstr;
412 $sth->execute() or die $sth->errstr;
416 foreach my $log_email (
417 qsearch('log_email',{ 'min_level' => { 'op' => '>=', 'value' => '2' } })
419 $log_email->min_level($levelmap{$log_email->min_level});
420 my $error = $log_email->replace;
427 FS::upgrade_journal->set_done('log__remap_levels');
437 L<FS::Record>, schema.html from the base documentation.