Logging methods
Always pass a source identifier as the second argument. It makes filtering the system log fast and reliable. See the debugging guide for how to use these effectively.
gs.log('General message'); // Info level — System Log
gs.log('Processing record', 'MyScriptName'); // With source — filterable
gs.info('Processing started', 'MyScript'); // Info level
gs.warn('Queue depth high', 'JobMonitor'); // Warning level
gs.error('Failed to process', 'MyScript'); // Error level
gs.debug('Step complete', 'MyScript'); // Debug — visible when session debug enabled
User context
gs.getUserID(); // sys_id of currently logged-in user
gs.getUserName(); // Username (login name) e.g. "john.smith"
gs.getUser().getDisplayName(); // Current user's display name
gs.getUser().getEmail(); // User's email address
gs.hasRole('itil'); // Boolean — does current user have this role?
gs.hasRole('itil,admin'); // Boolean — has either role (OR, not AND)
gs.isInteractive(); // True if user is in browser session (not API/background)
gs.getSession().isInteractive(); // Same as above
gs.getSession().getClientIP(); // Client IP address
For more on roles and how they work, see Roles vs Groups in ServiceNow. For getUserID patterns in scripts and ACLs, see gs.getUserID() complete reference.
Date and time utilities
gs.now(); // Current date in UTC, in the user-defined format
gs.nowDateTime(); // Current date and time in the user-defined format (a String)
gs.nowGlideDateTime(); // GlideDateTime object with the current date and time
gs.beginningOfToday(); // Start of today in the session time zone, as a UTC timestamp
gs.endOfToday(); // End of today in the session time zone, as a UTC timestamp
gs.beginningOfThisWeek(); // Start of this week as a UTC timestamp
gs.endOfThisWeek(); // End of this week as a UTC timestamp
gs.beginningOfThisMonth(); // First day of this month 00:00
gs.endOfThisMonth(); // Last day of this month 23:59
gs.beginningOfLastMonth(); // First day of last month
gs.endOfLastMonth(); // Last day of last month
gs.beginningOfThisQuarter(); // Start of current quarter
gs.beginningOfThisYear(); // Jan 1 of current year
gs.daysAgo(7); // datetime 7 days ago
gs.daysAgoStart(7); // start of day 7 days ago (for range queries)
gs.daysAgoEnd(0); // end of today (for range queries)
gs.hoursAgo(24); // datetime 24 hours ago
gs.minutesAgo(30); // datetime 30 minutes ago
System properties
// Read a system property
gs.getProperty('glide.ui.home'); // Returns value or null
gs.getProperty('my.setting', 'default_value'); // Returns default if not found
// Set a system property (requires admin role)
gs.setProperty('my.setting', 'new_value');
gs.setProperty('my.setting', 'new_value', 'Description'); // With description
// Check before using
var endpoint = gs.getProperty('my.api.endpoint');
if (!endpoint) {
gs.error('System property my.api.endpoint is not configured', 'MyIntegration');
return;
}
The GlideSystem reference notes that gs.setProperty() causes a system-wide cache flush, so avoid calling it often. For the full gs.getProperty() reference including type handling and caching, see gs.getProperty() complete reference.
Event management
// Queue an event that fires a notification or Script Action
gs.eventQueue(
'incident.priority.changed', // Event name (must exist in Event Registry)
current, // GlideRecord object (event source)
current.getValue('assigned_to'), // param1
current.getValue('priority') // param2
);
// Schedule event for future execution
gs.eventQueueScheduled(
'event.name',
current,
param1,
param2,
scheduledTime // Date and time to process this event
);
String and encoding utilities
gs.generateGUID(); // Generate a GUID for use as a unique identifier
gs.urlEncode(url); // Encode non-ASCII characters, unsafe ASCII characters and spaces
gs.urlDecode(encodedUrl); // Replace UTF-8 encoded characters with ASCII characters
gs.base64Encode('my string'); // Create a base64 string from the string
gs.base64Decode('bXkgc3RyaW5n'); // Return an ASCII string from the base64 string
gs.xmlToJSON(xmlString); // Take an XML string and return a JSON object
// Global scripts: GlideStringUtil
GlideStringUtil.unEscapeHTML(htmlString); // Replace HTML escape codes with the characters they stand for
GlideStringUtil.urlEncode(url); // Global scope only
These six gs methods are listed on the Scoped GlideSystem reference. The Global GlideSystem reference does not list them, so if you call them from a global script, test them on a sub-production instance first. For HTML decoding and URL encoding in global scripts, the GlideStringUtil reference documents unEscapeHTML() and urlEncode().
Number formatting
gs.getProperty('glide.currency.code', 'USD'); // Instance currency code
// Format a number with locale settings
// Note: for currency/number display, GlideLocale is typically used
// gs provides basic utilities
Session and context
gs.getSession(); // GlideSession object
gs.getSession().putClientData('key', 'value'); // Store value in session
gs.getSession().getClientData('key'); // Retrieve from session (string)
gs.getCurrentScopeName(); // Current application scope name
Impersonation utilities
// Check if currently running as background/system
if (!gs.isInteractive()) {
// Running via API, Scheduled Job, or background script
gs.log('Non-interactive session — skipping UI checks', 'MyScript');
}
// Get the real user when impersonating
gs.getImpersonatingUserName(); // Name of the impersonating user, or null if not impersonating
gs.getImpersonatingUserDisplayName(); // Display name of the impersonating user
Table and schema utilities
// Check if a table exists
var tableExists = gs.tableExists('my_custom_table');
Sending emails programmatically
// Send a simple email from a script
var email = new GlideEmailOutbound();
email.setSubject('Incident Alert: ' + current.getValue('number'));
email.setBody('A new P1 incident has been created: ' + current.getValue('short_description'));
email.addRecipient(current.assigned_to.getDisplayValue());
email.addAddress('to', 'manager@company.com');
email.save();
Password and security utilities
gs.generateGUID(); // Use for generating unique identifiers
// For generating passwords:
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var password = '';
for (var i = 0; i < 12; i++) {
password += chars.charAt(Math.floor(Math.random() * chars.length));
}
Related scripting guides:
- gs.getUserID() — complete reference with patterns
- gs.getProperty() — system properties in scripts
- Debugging scripts — using gs.log() effectively
- Script Includes — gs usage in server-side libraries
- Business Rule types — gs context in each rule type
gs.log(), gs.info(), gs.warn(), gs.error() — logging methods
The gs logging methods write to the System Log and are your primary debugging and operational logging tool for server-side scripts. They differ in severity level and visibility:
// gs.log(message, source) — general purpose
gs.log('Processing complete: ' + recordCount + ' records updated', 'DailyJob');
// gs.info(message, source) — informational, lower noise
gs.info('Integration sync started', 'SAPConnector');
// gs.warn(message, source) — something unexpected but non-fatal
gs.warn('User not found for email: ' + emailAddress, 'UserProvisioning');
// gs.error(message, source) — error condition, always visible
gs.error('Failed to call external API: ' + errorMsg, 'IntegrationHandler');
// Without source parameter — source shows as empty string
gs.log('Simple debug message');
The source parameter (second argument) is critical for production code — it lets you filter the System Log by your component name. Always provide a source string in any Script Include or Scheduled Job that could generate log volume. In Scripts - Background debugging sessions, the source can be anything descriptive. The Scoped GlideSystem reference has no gs.log(); in a scoped application use gs.info(), gs.warn(), gs.error(), or gs.debug().
gs.getProperty() and gs.setProperty()
// Read a system property (second arg is default if property doesn't exist)
var maxRetries = parseInt(gs.getProperty('my_app.integration.max_retries', '3'));
var apiEndpoint = gs.getProperty('my_app.api.base_url', 'https://api.example.com');
// Set a property programmatically (admin rights required)
gs.setProperty('my_app.last_sync_time', gs.nowDateTime());
// Check property existence
var endpoint = gs.getProperty('my_app.endpoint');
if (!endpoint) {
gs.error('Required property my_app.endpoint is not configured', 'MyApp');
return;
}
System properties are the correct mechanism for externalising configuration from scripts. API endpoints, feature flags, threshold values, email addresses — anything that varies between environments or might need to change without a code deployment should be a system property. Never hardcode these values in scripts. See the gs.getProperty deep dive for more on property management patterns.
gs.getUserID(), gs.getUserName(), gs.getUser()
// Get current user's sys_id
var userId = gs.getUserID(); // returns sys_id string
// Get current user's username (login name, not display name)
var username = gs.getUserName(); // "john.smith", not "John Smith"
// Get the full GlideUser object (more expensive — use when you need user attributes)
var user = gs.getUser();
var firstName = user.getFirstName();
var email = user.getEmail();
var companyId = user.getCompanyID();
// Check if user has a specific role
if (gs.hasRole('admin')) {
// Show admin-only features
}
if (gs.hasRole('itil') || gs.hasRole('x_myapp.editor')) {
// User has either the platform itil role or the custom app editor role
}
In Business Rules and ACL scripts, gs.getUserID() runs as the user who triggered the operation. In Scheduled Jobs, it runs as the admin user configured for the job. Understanding whose context gs.getUserID() returns — and when it might return the system user vs a real user — is important for building scripts that behave correctly across both interactive and automated contexts. The Global GlideUser reference and the Scoped GlideUser reference both list getFirstName(), getEmail(), getCompanyID() and getDisplayName(), and neither lists getFullName(), so use getDisplayName() for the user's name.
gs.now(), gs.nowDateTime(), gs.daysAgo()
// Current date in UTC, in the user-defined format
var today = gs.now(); // current date in UTC, user-defined format, e.g. "2026-05-15"
// Current date and time in the user-defined format
var now = gs.nowDateTime(); // "2026-05-15 14:30:00"
// Date utility methods for queries
var sevenDaysAgo = gs.daysAgo(7); // date 7 days ago
var startOfMonth = gs.beginningOfThisMonth();
var endOfMonth = gs.endOfThisMonth();
var startOfWeek = gs.beginningOfThisWeek();
// Using in encoded queries
var recentQuery = 'opened_at>' + gs.daysAgo(30);
gr.addEncodedQuery(recentQuery);
// Or with the javascript: syntax in encoded queries
// 'opened_atONThis month@javascript:gs.beginningOfThisMonth()@javascript:gs.endOfThisMonth()'
gs.include() — loading Script Includes
Script Includes load automatically when you instantiate them with new ScriptIncludeName(). You rarely need gs.include() directly. The exception: loading utility libraries that are not instantiated as classes — older-style Script Includes that expose functions rather than a class. Modern development practice uses class-based Script Includes; if you encounter gs.include() in legacy code, it is loading a functional Script Include.
gs in Client Scripts — the restriction
The gs object is a server-side only API. It is not available in Client Scripts or UI Scripts. Client Scripts have a different global context with different available APIs — g_form, g_user, GlideAjax. If you see gs.getProperty() in a Client Script, it will silently fail or throw an error. The pattern for making server-side data available to client scripts is either g_scratchpad in a Display Business Rule or a GlideAjax call to a Script Include that uses gs.
Related scripting guides: gs.getProperty · gs.getUserID · GlideRecord · Business Rules · Debugging
gs as the backbone of server-side scripting
The gs object is present in every server-side script context — Business Rules, Script Includes, Scheduled Jobs, ACL Scripts, UI Actions, and Processors. It is the Swiss Army knife of ServiceNow scripting: user context, logging, property access, date utilities, session information, and more. Fluency with gs methods is a prerequisite for fluency with any server-side ServiceNow scripting. Developers who know the full gs API — not just gs.log() and gs.getUserID() but also gs.getSession(), gs.isInteractive(), gs.getImpersonatingUserName() — write noticeably tighter, more contextually-aware scripts. Study the full gs object reference alongside the GlideRecord API for a complete picture of what is available in every server-side script context. The technical interview questions frequently test gs method knowledge alongside GlideRecord patterns. Make the gs API reference part of your regular study materials, revisit it when you encounter edge cases in production scripting, and build fluency through practice rather than memorisation.