Zum Hauptteil springen

The out of the box experience using ServiceNow server side logging is not great. Sorting logs by timestamp is not very useful, since many log messages are created with the same timestamp, due to the timestamp only being resolved to the second, not to the millisecond. It can be hard to figure out which log messages happened during one interaction and which are related to a specific record.

 

A Better Logging Approach

Using the default logging approach  gs.log()  to encode additional information we want to record in the log is error prone and high effort. Instead we want to wrap  gs.log() in a Script Include and include additional functionality to make the log message sortable within a transaction and to always automatically store the record the log message is related to.

We also want to see logs related to specific records directly in the record view of that record. Seeing the log messages on the record view can be tremendously helpful when diagnosing an issue. It may also allow more technical business user to assist in diagnosis. We accomplish this using a Relationship (sys_relationship) which will allow us to add the restricted log view to the related list section of any table.

 

Script Include

function Log(record, messagePrefix, sourcePrefix) {
  var order = 1;
  var id = record.getUniqueValue();
  var datePrefix = new GlideDateTime().getDisplayValueInternal();
  var orderPadding = '0000';

  function getOrder() {
    var paddedOrder = orderPadding + order++;
    return paddedOrder.substring(paddedOrder.length - orderPadding.length);
  }

  function log(message) {
    gs.log(datePrefix + '-' + getOrder() + ' ' + messagePrefix + ': ' + message, sourcePrefix + '.' + id);
  }

  return log;
}

 

 

Relationship

Applies to table: Global (global)
Queries from table: Log Entry (syslog)

(function refineQuery(current, parent) {
  current.addEncodedQuery('sourceLIKE' + parent.getUniqueValue());
  current.orderByDesc('message');
})(current, parent);

 

 
Usage
function checkIncidentAssignmentGroup(current) {
  var logger = Log(current, 'checkIncidentAssignmentGroup', 'ITSM');
  logger('checking incident assignment group');
  var assignmentGroupIsNull = current.getValue('assignment_group') == null;
  if(assignmentGroupIsNull) {
    logger('assignment group is empty');
  } else {
    logger('assignment group is ' + current.getValue('assignment_group'));
  }
  logger('successfully checked incident assignment group');
  return assignmentGroupIsNull;
}

 

Output
Log Entries
Log Entries

 

Summary

Using this logging approach we can:

  • See which log messages belong to a specific record and view them directly on the record form.
  • Be sure that we are viewing the log messages in the order they were created.
  • Know during which specific interaction the log messages were created.