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;
14 FS::log - Object methods for log records
20 $record = new FS::log \%hash;
21 $record = new FS::log { 'column' => 'value' };
23 $error = $record->insert;
25 $error = $new_record->replace($old_record);
27 $error = $record->delete;
29 $error = $record->check;
33 An FS::log object represents a log entry. FS::log inherits from
34 FS::Record. The following fields are currently supported:
38 =item lognum - primary key
40 =item _date - Unix timestamp
42 =item agentnum - L<FS::agent> to which the log pertains. If it involves a
43 specific customer, package, service, invoice, or other agent-specific object,
44 this will be set to that agentnum.
46 =item tablename - table name to which the log pertains, if any.
48 =item tablenum - foreign key to that table.
50 =item level - log level: 'debug', 'info', 'notice', 'warning', 'error',
51 'critical', 'alert', 'emergency'.
53 =item message - contents of the log entry
63 Creates a new log entry. Use FS::Log instead of calling this directly,
70 =item insert [ CONTEXT... ]
72 Adds this record to the database. If there is an error, returns the error,
73 otherwise returns false.
75 CONTEXT may be a list of context tags to attach to this record.
77 Will send emails according to the conditions in L<FS::log_email>.
82 # not using process_o2m for this, because we don't have a web interface
84 my $error = $self->SUPER::insert;
85 return $error if $error;
86 my $contexts = {}; #for quick checks when sending emails
88 my $context = FS::log_context->new({
89 'lognum' => $self->lognum,
92 $error = $context->insert;
93 return $error if $error;
96 foreach my $log_email (
102 'value' => $self->level,
107 # shouldn't be a lot of these, so not packing this into the qsearch
108 next if $log_email->context && !$contexts->{$log_email->context};
109 my $msg_template = qsearchs('msg_template',{ 'msgnum' => $log_email->msgnum });
110 unless ($msg_template) {
111 warn "Could not send email when logging, could not load message template for logemailnum " . $log_email->logemailnum;
114 my $emailerror = $msg_template->send(
115 'msgtype' => 'admin',
116 'to' => $log_email->to_addr,
118 'loglevel' => $FS::Log::LEVELS{$self->level}, # which has hopefully been loaded...
119 'logcontext' => $log_email->context, # use the one that triggered the email
120 'logmessage' => $self->message,
123 warn "Could not send email when logging: $emailerror" if $emailerror;
128 # these methods can be inherited from FS::Record
130 sub delete { die "Log entries can't be modified." };
132 sub replace { die "Log entries can't be modified." };
136 Checks all fields to make sure this is a valid example. If there is
137 an error, returns the error, otherwise returns false. Called by the insert
146 $self->ut_numbern('lognum')
147 || $self->ut_number('_date')
148 || $self->ut_numbern('agentnum')
149 || $self->ut_foreign_keyn('agentnum', 'agent', 'agentnum')
150 || $self->ut_textn('tablename')
151 || $self->ut_numbern('tablenum')
152 || $self->ut_number('level')
153 || $self->ut_anything('message')
155 return $error if $error;
157 if ( my $tablename = $self->tablename ) {
158 my $dbdef_table = dbdef->table($tablename)
159 or return "tablename '$tablename' does not exist";
160 $error = $self->ut_foreign_key('tablenum',
162 $dbdef_table->primary_key);
163 return $error if $error;
171 Returns the context for this log entry, as an array, from least to most
178 map { $_->context } qsearch({
179 table => 'log_context',
180 hashref => { lognum => $self->lognum },
181 order_by => 'ORDER BY logcontextnum ASC',
193 Returns a qsearch hash expression to search for parameters specified in
194 HASHREF. Valid parameters are:
200 =item date - arrayref of start and end date
202 =item level - either a specific level, or an arrayref of min and max level
204 =item context - a context string that the log entry must have. This may
205 change in the future to allow searching for combinations of context strings.
207 =item object - any database object, to find log entries related to it.
209 =item tablename, tablenum - alternate way of specifying 'object'.
211 =item custnum - a customer number, to find log entries related to the customer
212 or any of their subordinate objects (invoices, packages, etc.).
214 =item message - a text string to search in messages. The search will be
215 a case-insensitive LIKE with % appended at both ends.
221 # used for custnum search: all tables with custnums
224 sub _setup_table_stubs {
250 my $pkey = dbdef->table($table)->primary_key;
252 "log.tablename = '$table' AND ".
253 "EXISTS(SELECT 1 FROM $table WHERE log.tablenum = $table.$pkey AND ".
254 "$table.custnum = "; # needs a closing )
258 "(log.tablename LIKE 'svc_%' OR log.tablename = 'cust_svc') AND ".
259 "EXISTS(SELECT 1 FROM cust_svc JOIN cust_pkg USING (svcnum) WHERE ".
260 "cust_pkg.custnum = "; # needs a closing )
264 my ($class, $params) = @_;
271 if ( $params->{'agentnum'} =~ /^(\d+)$/ ) {
280 if ( $params->{'custnum'} =~ /^(\d+)$/ ) {
281 _setup_table_stubs() unless @table_stubs;
283 my @orwhere = map { "( $_ $custnum) )" } @table_stubs;
284 push @where, join(' OR ', @orwhere);
291 if ( ref $params->{'level'} eq 'ARRAY' ) {
292 my ($min, $max) = @{ $params->{'level'} };
293 if ( $min =~ /^\d+$/ ) {
294 push @where, "log.level >= $min";
296 if ( $max =~ /^\d+$/ ) {
297 push @where, "log.level <= $max";
299 } elsif ( $params->{'level'} =~ /^(\d+)$/ ) {
300 push @where, "log.level = $1";
307 if ( ref $params->{'date'} eq 'ARRAY' ) {
308 my ($beg, $end) = @{ $params->{'date'} };
309 if ( $beg =~ /^\d+$/ ) {
310 push @where, "log._date >= $beg";
312 if ( $end =~ /^\d+$/ ) {
313 push @where, "log._date <= $end";
321 if ( $params->{'object'} and $params->{'object'}->isa('FS::Record') ) {
322 my $table = $params->{'object'}->table;
323 my $pkey = dbdef->table($table)->primary_key;
324 my $tablenum = $params->{'object'}->get($pkey);
325 if ( $table and $tablenum ) {
326 push @where, "log.tablename = '$table'", "log.tablenum = $tablenum";
328 } elsif ( $params->{'tablename'} =~ /^(\w+)$/ ) {
330 if ( $params->{'tablenum'} =~ /^(\d+)$/ ) {
331 push @where, "log.tablename = '$table'", "log.tablenum = $1";
339 if ( $params->{'message'} ) { # can be anything, really, so escape it
340 my $quoted_message = dbh->quote('%' . $params->{'message'} . '%');
341 my $op = (driver_name eq 'Pg' ? 'ILIKE' : 'LIKE');
342 push @where, "log.message $op $quoted_message";
349 if ( $params->{'context'} ) {
350 my $quoted = dbh->quote($params->{'context'});
351 if ( $params->{'context_height'} =~ /^\d+$/ ) {
352 my $subq = 'SELECT context FROM log_context WHERE log.lognum = log_context.lognum'.
353 ' ORDER BY logcontextnum DESC LIMIT '.$params->{'context_height'};
355 "EXISTS(SELECT 1 FROM ($subq) AS log_context_x WHERE log_context_x.context = $quoted)";
358 "EXISTS(SELECT 1 FROM log_context WHERE log.lognum = log_context.lognum ".
359 "AND log_context.context = $quoted)";
363 # agent virtualization
364 my $access_user = $FS::CurrentUser::CurrentUser;
365 push @where, $access_user->agentnums_sql(
367 viewall_right => 'Configuration',
373 $extra_sql .= 'WHERE ' . join(' AND ', @where) if @where;
374 my $count_query = 'SELECT COUNT(*) FROM log '.$extra_sql;
379 'extra_sql' => $extra_sql,
380 'count_query' => $count_query,
381 'order_by' => 'ORDER BY _date ASC',
382 #addl_from, not needed
387 my ($class, %opts) = @_;
389 return if FS::upgrade_journal->is_done('log__remap_levels');
391 tie my %levelmap, 'Tie::IxHash',
392 2 => 1, #notice -> info
393 6 => 5, #alert -> critical
394 7 => 5, #emergency -> critical
397 # this method should never autocommit
398 # should have been set in upgrade, but just in case...
399 local $FS::UID::AutoCommit = 0;
401 # in practice, only debug/info/warning/error appear to have been used,
402 # so this probably won't do anything, but just in case
403 foreach my $old (keys %levelmap) {
404 # FS::log has no replace method
405 my $sql = 'UPDATE log SET level=' . dbh->quote($levelmap{$old}) . ' WHERE level=' . dbh->quote($old);
406 warn $sql unless $opts{'quiet'};
407 my $sth = dbh->prepare($sql) or die dbh->errstr;
408 $sth->execute() or die $sth->errstr;
412 foreach my $log_email (
413 qsearch('log_email',{ 'min_level' => 2 }),
414 qsearch('log_email',{ 'min_level' => 6 }),
415 qsearch('log_email',{ 'min_level' => 7 }),
417 $log_email->min_level($levelmap{$log_email->min_level});
418 my $error = $log_email->replace;
425 FS::upgrade_journal->set_done('log__remap_levels');
435 L<FS::Record>, schema.html from the base documentation.