Skip to content

Commit eb2acd8

Browse files
authored
Non prod logger utils (#1677)
1 parent 7c1eaa3 commit eb2acd8

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
var LoggingUtils = Class.create();
2+
LoggingUtils.prototype = {
3+
initialize: function() {
4+
},
5+
6+
/**
7+
* @param {string} message The message to log.
8+
* @param {string} [type='info'] The type of log. Options: 'info', 'warn', 'error'.
9+
* @returns {void}
10+
*
11+
* This utility function logs a message only if the current instance is non-production.
12+
* Use it in other server-side scripts like this:
13+
* var logUtil = new LoggingUtils();
14+
* logUtil.log('This message will only show in dev and test environments.');
15+
*/
16+
log: function(message, type) {
17+
// Get the current instance name from a system property
18+
var instanceName = gs.getProperty('instance_name');
19+
20+
// You must define your production instance name.
21+
// For example, if your production instance is 'mycompanyprod'.
22+
var productionInstanceName = 'mycompanyprod';
23+
24+
// Check if the current instance name is NOT the production instance name
25+
if (instanceName && instanceName != productionInstanceName) {
26+
type = type || 'info';
27+
28+
// Determine the correct logging function based on the specified type
29+
switch (type) {
30+
case 'warn':
31+
gs.warn(message);
32+
break;
33+
case 'error':
34+
gs.error(message);
35+
break;
36+
default:
37+
gs.log(message);
38+
break;
39+
}
40+
}
41+
},
42+
43+
type: 'LoggingUtils'
44+
};
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
To create a logging utility in a ServiceNow Script Include that only logs in non-production environments, you can follow these steps:
2+
3+
4+
Create a new Script Include.
5+
Define a utility class with a logging function.
6+
Inside the function, get the instance name and use conditional logic to check if it matches the production instance name.
7+
If the instance is non-production, execute the logging command.
8+
Call this utility from other server-side scripts.
9+
10+
11+
This method centralizes your logging logic, making it easy to manage.
12+
Step 1: Create the Script Include
13+
In the main navigation, type Script Includes and select it under System Definition.
14+
Click New to create a new record.
15+
Fill out the form with the following details:
16+
Name: LoggingUtils
17+
Accessible from: All application scopes (This allows you to call the function from anywhere).
18+
Client callable: Unchecked (This is a server-side utility).
19+
20+
21+
22+
23+
// Instantiate the Script Include
24+
var logUtil = new LoggingUtils();
25+
26+
// Use the log() function to log a message
27+
logUtil.log('Hackertoberfest', 'info');

0 commit comments

Comments
 (0)