diff --git a/Server-Side Components/Script Includes/NonProdLogUtils/LogUtilsNonProd.js b/Server-Side Components/Script Includes/NonProdLogUtils/LogUtilsNonProd.js new file mode 100644 index 0000000000..9884ccaab8 --- /dev/null +++ b/Server-Side Components/Script Includes/NonProdLogUtils/LogUtilsNonProd.js @@ -0,0 +1,44 @@ +var LoggingUtils = Class.create(); +LoggingUtils.prototype = { + initialize: function() { + }, + + /** + * @param {string} message The message to log. + * @param {string} [type='info'] The type of log. Options: 'info', 'warn', 'error'. + * @returns {void} + * + * This utility function logs a message only if the current instance is non-production. + * Use it in other server-side scripts like this: + * var logUtil = new LoggingUtils(); + * logUtil.log('This message will only show in dev and test environments.'); + */ + log: function(message, type) { + // Get the current instance name from a system property + var instanceName = gs.getProperty('instance_name'); + + // You must define your production instance name. + // For example, if your production instance is 'mycompanyprod'. + var productionInstanceName = 'mycompanyprod'; + + // Check if the current instance name is NOT the production instance name + if (instanceName && instanceName != productionInstanceName) { + type = type || 'info'; + + // Determine the correct logging function based on the specified type + switch (type) { + case 'warn': + gs.warn(message); + break; + case 'error': + gs.error(message); + break; + default: + gs.log(message); + break; + } + } + }, + + type: 'LoggingUtils' +}; diff --git a/Server-Side Components/Script Includes/NonProdLogUtils/README.md b/Server-Side Components/Script Includes/NonProdLogUtils/README.md new file mode 100644 index 0000000000..22e33ee799 --- /dev/null +++ b/Server-Side Components/Script Includes/NonProdLogUtils/README.md @@ -0,0 +1,27 @@ +To create a logging utility in a ServiceNow Script Include that only logs in non-production environments, you can follow these steps: + + +Create a new Script Include. +Define a utility class with a logging function. +Inside the function, get the instance name and use conditional logic to check if it matches the production instance name. +If the instance is non-production, execute the logging command. +Call this utility from other server-side scripts. + + +This method centralizes your logging logic, making it easy to manage. +Step 1: Create the Script Include +In the main navigation, type Script Includes and select it under System Definition. +Click New to create a new record. +Fill out the form with the following details: +Name: LoggingUtils +Accessible from: All application scopes (This allows you to call the function from anywhere). +Client callable: Unchecked (This is a server-side utility). + + + + +// Instantiate the Script Include +var logUtil = new LoggingUtils(); + +// Use the log() function to log a message +logUtil.log('Hackertoberfest', 'info');