Skip to main content
Version: 5.0.0

N|Solid API

Table of Contents N|Solid API

nsolid.start()

Another option, which can be useful if you don't have access to static configuration data, is to use the N|Solid API from within your application. For example, if you have a configuration management platform or database that knows the hostname and port to your Console, you may obtain it and then invoke nsolid.start() to connect and begin reporting metrics. This can be done at any time, as long as your process is not already connected to an N|Solid Console. The keys are the same as the package.json keys documented above, with the following difference:

  • version is specified as appVersion

Example:

const nsolid = require('nsolid')
nsolid.start({
command: 'nsolid-command-host.local:9001',
tags: ['nsolid-awesome', 'Auth service'],
app: 'nsolid-awesome',
appVersion: '1.0.0'
})

nsolid.appName

Get the N|Solid app name (equal to nsolid.app getter).

const nsolid = require('nsolid')
nsolid.appName
'nsolid-awesome'

nsolid.appVersion

Get the N|Solid app version (taken from the package.json file).

const nsolid = require('nsolid')
nsolid.appVersion
'1.0.0'

nsolid.app

Get the N|Solid app name.

const nsolid = require('nsolid')
nsolid.app
'nsolid-awesome'

nsolid.clearFatalError()

const nsolid = require('nsolid')
process.on('uncaughtException', err => {
nsolid.clearFatalError(err)
proces.exit(1)
})

nsolid.config

Get the N|Solid application config.

const nsolid = require('nsolid')
nsolid.config
{
app: 'nsolid-awesome',
appVersion: '1.0.0',
blockedLoopThreshold: 200,
env: 'prod',
hostname: 'nsolid-host',
interval: 3000,
pauseMetrics: false,
pubkey: '<3',
statsdBucket: 'nsolid.${env}.${app}.${hostname}.${shortId}',
tags: ['nsolid-awesome', 'Auth service']
}

nsolid.getThreadName()

Get an N|Solid worker thread name.

const { Worker, isMainThread } = require('worker_threads');
const { getThreadName, setThreadName } = require('nsolid')

if (!isMainThread) {
console.log(getThreadName()) // ''
setThreadName('worker-parser')
console.log(getThreadName()) // worker-parser
return setTimeout(() => {}, 1000)
}
const worker = new Worker(__filename)

nsolid.id

Get the N|Solid agent id.

const nsolid = require('nsolid')
nsolid.id
'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'

nsolid.info()

It returns relevant information about the running process and platform is running on.

const nsolid = require('nsolid')
nsolid.info()
{
id: '14e708a4bdb1fc5763fa1f29a9567229ab1b1ac4',
app: 'beautiful-nsolid-app',
appVersion: '1.0.0',
tags: undefined,
pid: 855556,
processStart: 1600731441576,
nodeEnv: undefined,
execPath: 'your-beautiful-app-directory/beautiful-nsolid-app',
main: 'index.js',
arch: 'x64',
platform: 'linux',
hostname: 'NodeSource',
totalMem: 16302604288,
versions: {
node: '12.18.4',
nsolid: '4.0.0',
v8: '7.8.279.23-node.39',
uv: '1.38.0',
zlib: '1.2.11',
brotli: '1.0.7',
ares: '1.16.0',
modules: '72',
nghttp2: '1.41.0',
napi: '6',
llhttp: '2.1.2',
http_parser: '2.9.3',
openssl: '1.1.1g',
cldr: '37.0',
icu: '67.1',
tz: '2019c',
unicode: '13.0'
},
cpuCores: 4,
cpuModel: 'Intel(R) Core(TM) i7-7500U CPU @ 2.70GHz'
}

The nsolid.info() method can be called asynchronously too:

const nsolid = require('nsolid')
nsolid.info((err, info) => {
if (!err) {
// Yay!
}
})

nsolid.metrics()

It retrieves a list of enviroment and process metrics.

const nsolid = require('nsolid')
nsolid.metrics()
{
threadId: 0,
timestamp: 0,
activeHandles: 0,
activeRequests: 0,
heapTotal: 4464640,
totalHeapSizeExecutable: 524288,
totalPhysicalSize: 3685528,
totalAvailableSize: 2194638976,
heapUsed: 2666008,
heapSizeLimit: 2197815296,
mallocedMemory: 8192,
externalMem: 833517,
peakMallocedMemory: 91744,
numberOfNativeContexts: 1,
numberOfDetachedContexts: 0,
gcCount: 1,
gcForcedCount: 0,
gcFullCount: 0,
gcMajorCount: 0,
gcDurUs99Ptile: 812,
gcDurUsMedian: 812,
dnsCount: 0,
httpClientAbortCount: 0,
httpClientCount: 0,
httpServerAbortCount: 0,
httpServerCount: 0,
dns99Ptile: 0,
dnsMedian: 0,
httpClient99Ptile: 0,
httpClientMedian: 0,
httpServer99Ptile: 0,
httpServerMedian: 0,
loopIdleTime: 0,
loopIterations: 0,
loopIterWithEvents: 0,
eventsProcessed: 0,
eventsWaiting: 0,
providerDelay: 0,
processingDelay: 0,
loopUtilization: 1,
res5s: 0,
res1m: 0,
res5m: 0,
res15m: 0,
loopTotalCount: 0,
loopAvgTasks: 0,
loopEstimatedLag: 40.416415,
loopIdlePercent: 0,
title: 'nsolid',
user: 'NodeSource',
uptime: 0,
systemUptime: 96314,
freeMem: 2586660864,
blockInputOpCount: 0,
blockOutputOpCount: 0,
ctxSwitchInvoluntaryCount: 14,
ctxSwitchVoluntaryCount: 21,
ipcReceivedCount: 0,
ipcSentCount: 0,
pageFaultHardCount: 0,
pageFaultSoftCount: 1929,
signalCount: 0,
swapCount: 0,
rss: 31719424,
load1m: 2.79,
load5m: 2.52,
load15m: 2.47,
cpuUserPercent: 86.061918,
cpuSystemPercent: 15.533329,
cpuPercent: 101.595247,
cpu: 101.595247
}

If callback is passed, it returns the metrics asynchronously:

const nsolid = require('nsolid')
nsolid.metrics((err, metrics) => {
if (!err) {
// Yay!! All the metrics are in store in metrics param
}
})

See Metrics in detail for more information about each metric.

nsolid.metricsPaused

Whether the agent is currently retrieving metrics or not.

const nsolid = require('nsolid')
nsolid.metricsPaused
false

See nsolid.pauseMetrics()

nsolid.onLicense(OnLicenseHandler)

Registers a listener to be called anytime a new license is set in the NSolid runtime.

  • OnLicenseHandler is the handler of the actual listener.
const nsolid = require('nsolid')
nsolid.onLicense(({ licensed, expired }) => {
if (expired) {
Logger.error('Invalid license!')
return
}
doSomethingAwesome()
})

nsolid.packages()

It retrieves the list of packages listed in the package.json file and its dependencies, it returns a list of all packages that can be required by walking through all directories that could contain a module.

const nsolid = require('nsolid')
nsolid.packages()
[
{
path: 'nsolid-service/node_modules/js-tokens',
name: 'js-tokens',
version: '4.0.0',
main: 'index.js',
dependencies: [],
required: false
},
{
path: 'nsolid-service/node_modules/important-package',
name: 'important-package',
version: '3.0.0',
main: 'main.js',
dependencies: ['../express', '../object-assign'],
required: false
},
...
]

The nsolid.packages() method has async implementation too:

const nsolid = require('nsolid')
nsolid.packages((err, packages) => {
if (!err) {
console.log(packages)
}
})
[
{
path: 'your-beautiful-app-directory/beautiful-nsolid-app',
name: 'beautiful-nsolid-app',
version: '1.5.2',
main: 'index.js',
dependencies: [],
required: false
}
]

nsolid.pauseMetrics()

It pauses the process metrics collection, and do nothing if metrics were already paused (this method must be called on the main thread).

const nsolid = require('nsolid')
nsolid.pauseMetrics()

See nsolid.metricsPaused.

nsolid.processStart

It gets the start date of the process in milliseconds.

const nsolid = require('nsolid')
nsolid.processStart
1600730465456

nsolid.profile([duration])

This is the way to trigger a CPU profile programmatically from within your application and have the resulting profile saved on your N|Solid console. The profile duration 600000 milliseconds, which is the default if none is specified, and profiler can be stoped before the duration expires.

  • duration is the duration in milliseconds of the Cpu profile (600000 milliseconds is the default duration).
const nsolid = require('nsolid')
nsolid.profile(600000 /* durationMilliseconds */, err => {
if (err) {
// The profile could not be started!
}
})

The CPU profiler can be triggered in a synchronous way:

const nsolid = require('nsolid')
try {
nsolid.profile(600000 /* durationMilliseconds */)
} catch (err) {
// The profile could not be started!
}

nsolid.profileEnd()

To complete the profile before the duration expires, call profileEnd method:

const nsolid = require('nsolid')
nsolid.profileEnd(err => {
if (err) {
// Error stopping profiler (may it was not running)
}
})

nsolid.resumeMetrics()

It resumes the process metrics collection, and does nothing if metrics were already resumed (this method must be called on the main thread).

const nsolid = require('nsolid')
nsolid.resumeMetrics()

nsolid.saveFatalError(error)

If you must exit asynchronously from an uncaughtException handler it is still possible to report the exception by passing it to nsolid.saveFatalError() prior to shutting down.

const nsolid = require('nsolid')
process.on('uncaughtException', err => {
nsolid.saveFatalError(err)
proces.exit(1)
})

nsolid.setThreadName(name)

If it is preferred to handle workers threads with names, this could be achieved by using the nsolid.setThreadName(name) method.

const { Worker, isMainThread } = require('worker_threads');
const { getThreadName, setThreadName } = require('nsolid')

if (!isMainThread) {
console.log(getThreadName()) // ''
setThreadName('worker-renamed')
console.log(getThreadName()) // worker-renamed
return setTimeout(() => {}, 1000)
} else {
const worker = new Worker(__filename)
}

The main thread can also have a name

const { isMainThread } = require('worker_threads');
const { setThreadName } = require('nsolid')

if (isMainThread) setThreadName('app')

A worker (or the main thread) can be named only with strings, otherwise, an exception will be thrown.

const { Worker, isMainThread } = require('worker_threads');
const { getThreadName, setThreadName } = require('nsolid')

if (!isMainThread) {
try {
setThreadName(null)
} catch (err) { /** TypeError [ERR_INVALID_ARG_TYPE]: The "name" argument must be of type string. Received null */ }
} else {
const worker = new Worker(__filename)
}

nsolid.snapshot()

This is the way to take a heap snapshot programmatically from within your application and have the resulting snapshot(s) saved on your N|Solid console.

const nsolid = require('nsolid')
nsolid.snapshot(err => {
if (err) {
// The snapshot could not be created!
}
})

Snapshots can also be taken on a synchronous way:

const nsolid = require('nsolid')
try {
nsolid.snapshot()
} catch (err) {
// The snapshot could not be created!
}

nsolid.startupTimes()

It retrieves the startup times of the process in a high resolution array of [seconds, nanoseconds].

const nsolid = require('nsolid')
nsolid.startupTimes()
{
initialized_node: [ 0, 971137 ],
initialized_v8: [ 0, 181632 ],
loaded_environment: [ 0, 3874746 ]
}

The nsolid.startupTimes() method can be called asynchronously:

const nsolid = require('nsolid')
nsolid.startupTimes((err, startupTimes)) {
if (!err) {
console.log(startupTimes)
}
}
{
initialized_node: [ 0, 971137 ],
initialized_v8: [ 0, 181632 ],
loaded_environment: [ 0, 3874746 ]
}

nsolid.statsd

The nsolid.statsd object:

PropertyDescription
counter:Send a "counter" type value to statsd. Will use NSOLID_STATSD_BUCKET and NSOLID_STATSD_TAGS if configured.
format:Function that retrieves the statsd agent status.
gauge:Send a "gauge" type value to statsd. Will use NSOLID_STATSD_BUCKET and NSOLID_STATSD_TAGS if configured.
sendRaw:Send a raw string to statsd. Caller is required to comply to statsd format (terminating newline not required). An array of strings is also permissible, they will be sent newline separated. If connected via UDP, data sent via sendRaw() will be split up into 1400Kb batches to fit within a standard MTU window, this applies to newline separated strings or an array of strings passed to this interface.
set:Send a "set" type value to statsd. Will use NSOLID_STATSD_BUCKET and NSOLID_STATSD_TAGS if configured.
status:Function that retrieves the statsd agent status.
tcpIp:If configured, returns the ip address tcp statsd data will be sent to.
timing:Send a "timing" type value to statsd. Will use NSOLID_STATSD_BUCKET and NSOLID_STATSD_TAGS if configured.
udpIp:If configured, returns the ip address udp statsd data will be sent to.

The statsd statuses are:

  • unconfigured
  • initializing
  • connecting
  • ready

Usage example:

const nsolid = require('nsolid')
nsolid.statsd.status()
'unconfigured'

The nsolid.statsd.format object:

PropertyDescription
bucket:Returns the "bucket" string prepended to all auto-generated statsd metric strings.
counter:Format a "counter" string for name and value suitable for statsd.
gauge:Format a "gauge" string for name and value suitable for statsd.
set:Format a "set" string for name and value suitable for statsd.
timing:Format a "timing" string for name and value suitable for statsd.

Usage example:

const nsolid = require('nsolid')
nsolid.statsd.format.bucket()
''

nsolid.tags

Get the N|Solid app tags (taken from the package.json file or NSOLID_TAGS environment variable).

const nsolid = require('nsolid')
nsolid.tags
['nsolid-awesome', 'Auth service']

nsolid.traceStats

The nsolid.traceStats object:

PropertyDescription
dnsCount:The process's total number of DNS lookups performed
httpClientAbortCount:The process's total number of outgoing HTTP(S) client requests canceled due to inactivity.
httpClientCount:The process's total number of outgoing HTTP(S) client requests performed.
httpServerAbortCount:The process's total number of served incoming HTTP(S) requests canceled.
httpServerCount:The process's total number of incoming HTTP(s) requests served.

nsolid.zmq

The nsolid.zmq object:

PropertyDescription
status:Function that retrieves the zmq agent status.

The zmq agent statuses are:

  • buffering
  • connecting
  • initializing
  • ready
  • unconfigured

Usage example:

const nsolid = require('nsolid')
nsolid.zmq.status()
'ready'