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', 'warning', 'error', 'critical',
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
86 my $context_height = @_; # also for email check
87 foreach ( @_ ) { # ordered from least to most specific
88 my $context = FS::log_context->new({
89 'lognum' => $self->lognum,
92 $error = $context->insert;
93 return $error if $error;
94 $contexts->{$_} = $context_height--;
96 foreach my $log_email (
102 'value' => $self->level,
107 # shouldn't be a lot of log_email records, so not packing these checks into the qsearch
108 next if $log_email->context && !$contexts->{$log_email->context};
109 next if $log_email->context_height && ($contexts->{$log_email->context} > $log_email->context_height);
110 my $msg_template = qsearchs('msg_template',{ 'msgnum' => $log_email->msgnum });
111 unless ($msg_template) {
112 warn "Could not send email when logging, could not load message template for logemailnum " . $log_email->logemailnum;
115 my $emailerror = $msg_template->send(
116 'msgtype' => 'admin',
117 'to' => $log_email->to_addr,
119 'loglevel' => $FS::Log::LEVELS{$self->level}, # which has hopefully been loaded...
120 'logcontext' => $log_email->context, # use the one that triggered the email
121 'logmessage' => $self->message,
124 warn "Could not send email when logging: $emailerror" if $emailerror;
129 # these methods can be inherited from FS::Record
131 sub delete { die "Log entries can't be modified." };
133 sub replace { die "Log entries can't be modified." };
137 Checks all fields to make sure this is a valid example. If there is
138 an error, returns the error, otherwise returns false. Called by the insert
147 $self->ut_numbern('lognum')
148 || $self->ut_number('_date')
149 || $self->ut_numbern('agentnum')
150 || $self->ut_foreign_keyn('agentnum', 'agent', 'agentnum')
151 || $self->ut_textn('tablename')
152 || $self->ut_numbern('tablenum')
153 || $self->ut_number('level')
154 || $self->ut_anything('message')
156 return $error if $error;
158 if ( my $tablename = $self->tablename ) {
159 my $dbdef_table = dbdef->table($tablename)
160 or return "tablename '$tablename' does not exist";
161 $error = $self->ut_foreign_key('tablenum',
163 $dbdef_table->primary_key);
164 return $error if $error;
172 Returns the context for this log entry, as an array, from least to most
179 map { $_->context } qsearch({
180 table => 'log_context',
181 hashref => { lognum => $self->lognum },
182 order_by => 'ORDER BY logcontextnum ASC',
194 Returns a qsearch hash expression to search for parameters specified in
195 HASHREF. Valid parameters are:
201 =item date - arrayref of start and end date
203 =item level - either a specific level, or an arrayref of min and max level
205 =item context - a context string that the log entry must have. This may
206 change in the future to allow searching for combinations of context strings.
208 =item object - any database object, to find log entries related to it.
210 =item tablename, tablenum - alternate way of specifying 'object'.
212 =item custnum - a customer number, to find log entries related to the customer
213 or any of their subordinate objects (invoices, packages, etc.).
215 =item message - a text string to search in messages. The search will be
216 a case-insensitive LIKE with % appended at both ends.
222 # used for custnum search: all tables with custnums
225 sub _setup_table_stubs {
251 my $pkey = dbdef->table($table)->primary_key;
253 "log.tablename = '$table' AND ".
254 "EXISTS(SELECT 1 FROM $table WHERE log.tablenum = $table.$pkey AND ".
255 "$table.custnum = "; # needs a closing )
259 "(log.tablename LIKE 'svc_%' OR log.tablename = 'cust_svc') AND ".
260 "EXISTS(SELECT 1 FROM cust_svc JOIN cust_pkg USING (svcnum) WHERE ".
261 "cust_pkg.custnum = "; # needs a closing )
265 my ($class, $params) = @_;
272 if ( $params->{'agentnum'} =~ /^(\d+)$/ ) {
281 if ( $params->{'custnum'} =~ /^(\d+)$/ ) {
282 _setup_table_stubs() unless @table_stubs;
284 my @orwhere = map { "( $_ $custnum) )" } @table_stubs;
285 push @where, join(' OR ', @orwhere);
292 if ( ref $params->{'level'} eq 'ARRAY' ) {
293 my ($min, $max) = @{ $params->{'level'} };
294 if ( $min =~ /^\d+$/ ) {
295 push @where, "log.level >= $min";
297 if ( $max =~ /^\d+$/ ) {
298 push @where, "log.level <= $max";
300 } elsif ( $params->{'level'} =~ /^(\d+)$/ ) {
301 push @where, "log.level = $1";
308 if ( ref $params->{'date'} eq 'ARRAY' ) {
309 my ($beg, $end) = @{ $params->{'date'} };
310 if ( $beg =~ /^\d+$/ ) {
311 push @where, "log._date >= $beg";
313 if ( $end =~ /^\d+$/ ) {
314 push @where, "log._date <= $end";
322 if ( $params->{'object'} and $params->{'object'}->isa('FS::Record') ) {
323 my $table = $params->{'object'}->table;
324 my $pkey = dbdef->table($table)->primary_key;
325 my $tablenum = $params->{'object'}->get($pkey);
326 if ( $table and $tablenum ) {
327 push @where, "log.tablename = '$table'", "log.tablenum = $tablenum";
329 } elsif ( $params->{'tablename'} =~ /^(\w+)$/ ) {
331 if ( $params->{'tablenum'} =~ /^(\d+)$/ ) {
332 push @where, "log.tablename = '$table'", "log.tablenum = $1";
340 if ( $params->{'message'} ) { # can be anything, really, so escape it
341 my $quoted_message = dbh->quote('%' . $params->{'message'} . '%');
342 my $op = (driver_name eq 'Pg' ? 'ILIKE' : 'LIKE');
343 push @where, "log.message $op $quoted_message";
350 if ( $params->{'context'} ) {
351 my $quoted = dbh->quote($params->{'context'});
352 if ( $params->{'context_height'} =~ /^\d+$/ ) {
353 my $subq = 'SELECT context FROM log_context WHERE log.lognum = log_context.lognum'.
354 ' ORDER BY logcontextnum DESC LIMIT '.$params->{'context_height'};
356 "EXISTS(SELECT 1 FROM ($subq) AS log_context_x WHERE log_context_x.context = $quoted)";
359 "EXISTS(SELECT 1 FROM log_context WHERE log.lognum = log_context.lognum ".
360 "AND log_context.context = $quoted)";
364 # agent virtualization
365 my $access_user = $FS::CurrentUser::CurrentUser;
366 push @where, $access_user->agentnums_sql(
368 viewall_right => 'Configuration',
374 $extra_sql .= 'WHERE ' . join(' AND ', @where) if @where;
375 my $count_query = 'SELECT COUNT(*) FROM log '.$extra_sql;
380 'extra_sql' => $extra_sql,
381 'count_query' => $count_query,
382 'order_by' => 'ORDER BY _date ASC',
383 #addl_from, not needed
388 my ($class, %opts) = @_;
390 return if FS::upgrade_journal->is_done('log__remap_levels');
392 tie my %levelmap, 'Tie::IxHash',
393 2 => 1, #notice -> info
394 6 => 5, #alert -> critical
395 7 => 5, #emergency -> critical
398 # this method should never autocommit
399 # should have been set in upgrade, but just in case...
400 local $FS::UID::AutoCommit = 0;
402 # in practice, only debug/info/warning/error appear to have been used,
403 # so this probably won't do anything, but just in case
404 foreach my $old (keys %levelmap) {
405 # FS::log has no replace method
406 my $sql = 'UPDATE log SET level=' . dbh->quote($levelmap{$old}) . ' WHERE level=' . dbh->quote($old);
407 warn $sql unless $opts{'quiet'};
408 my $sth = dbh->prepare($sql) or die dbh->errstr;
409 $sth->execute() or die $sth->errstr;
413 foreach my $log_email (
414 qsearch('log_email',{ 'min_level' => 2 }),
415 qsearch('log_email',{ 'min_level' => 6 }),
416 qsearch('log_email',{ 'min_level' => 7 }),
418 $log_email->min_level($levelmap{$log_email->min_level});
419 my $error = $log_email->replace;
426 FS::upgrade_journal->set_done('log__remap_levels');
436 L<FS::Record>, schema.html from the base documentation.