Skip to content

Logging and tracing ​

The library logs nothing until you give it a logger. With one, you can see what a session is doing, down to every <rpc> and <rpc-reply>, and you can turn that on and off while the client is open.

A logger ​

A logger is any object with some of trace, debug, info, warn and error. Each takes a message and an optional context object. A level the logger has no method for is skipped, so console works as it is, and so does a partial adapter:

ts
const client = await connect({ transport, logger: console });

Loggers that take the context first, such as pino, need a small adapter:

ts
import { connect } from '@node-net/netconf';
import pino from 'pino';

const log = pino({ level: 'trace' });
const logger = Object.fromEntries(
  (['trace', 'debug', 'info', 'warn', 'error'] as const).map((level) => [
    level,
    (message: string, context?: Record<string, unknown>) =>
      log[level](context ?? {}, message),
  ]),
);

const client = await connect({ transport, logger });

Levels ​

logLevel is the least severe level passed to the logger. From most to least verbose:

LevelGets
'trace'every message sent and received, as send and receive with the XML
'debug'the session opening or failing, the device profile chosen, a late reply dropped, a device quirk cleaned up
'info'nothing yet: the library doesn't log at this level
'warn'everything the session's warning event reports, a capability the server didn't advertise (under capabilityCheck: 'warn'), cleanup that failed, such as an unlock or discard-changes
'error'a session event listener that threw
'silent'nothing

Each level includes the ones below it, so 'debug' also gets warnings and errors.

The default is 'trace': everything the logger has a method for. With console, that includes every message, so set a level when you want less:

ts
await connect({ transport, logger: console, logLevel: 'warn' });

Changing it while connected ​

You can change both the logger and the level on an open client. The change takes effect at once for everything the client does: the session, its operations and extensions, and the client itself.

ts
// or undefined to stop logging
client.setLogger(console);
// every <rpc> and <rpc-reply>
client.setLogLevel('trace');
// quiet again
client.setLogLevel('warn');

// the logger you set, or undefined
client.logger;
// 'warn'
client.logLevel;

An unknown level throws a TypeError and leaves the level as it was.

When tracing is off, message bodies aren't redacted or formatted at all, so it costs nothing to leave tracing available and switch it on when you need it. A logger that throws is ignored and never fails a request.

Watching messages ​

At 'trace', every message is logged as send or receive, with the XML in the context's xml.

To get the messages as data instead of log lines, listen for the session's 'message' event. It gives you the same redacted XML whatever the logger or level, and you can attach and remove it at any time. on() returns the function that removes it:

ts
const off = client.session.on('message', ({ direction, xml }) =>
  console.log(direction, xml),
);
// …
off();

The XML is compact, as it was sent. To indent it, parse it and serialise it again:

ts
import { parseXml, serializeXml } from '@node-net/netconf';

const off = client.session.on('message', ({ direction, xml }) => {
  const pretty = serializeXml(parseXml(xml), { indent: 2 });
  console.log(`${direction.toUpperCase()} ====\n${pretty}`);
});

console.log(element) indents an element by itself. Joining one into a string with + or a template gives compact XML, because that calls toString().

The hello exchange is over by the time connect() resolves, so a 'message' listener never sees it, and nor does a logger set later. To see the hellos, pass the logger to connect().

Redaction ​

Message bodies are redacted before they're logged or emitted. By default, redactXml replaces with *** all the text inside any element whose name looks secret, CDATA included and at any depth: names containing password, passphrase, secret, private-key, preshared, pre-shared, psk, community, key-string or cleartext, and names ending in key or token, such as authentication-key or access-token (but not public-key). It also hides the user and password in URLs, so ftp://admin:pw@host/f is logged as ftp://***@host/f. The rest of the message is logged exactly as sent or received, and malformed XML is still redacted.

Pass redact to connect() to use your own rule. redactXml is exported, so you can extend it:

ts
import { connect, redactXml } from '@node-net/netconf';

await connect({
  transport,
  logger,
  redact: (xml) =>
    redactXml(xml).replace(/<serial>[^<]*</g, '<serial>***<'),
});

redact: (xml) => xml turns redaction off. Only do that where the logs stay with you.

Timing ​

For RPC timing and outcomes, subscribe to the node:diagnostics_channel channel RPC_CHANNEL. It costs nothing when nobody subscribes:

ts
import diagnostics from 'node:diagnostics_channel';
import { RPC_CHANNEL } from '@node-net/netconf';

// m: { phase: 'start' | 'end' | 'error', sessionId, messageId,
//      operation, durationMs?, error? }
diagnostics.subscribe(RPC_CHANNEL, (m) => {
  if (m.phase === 'start') return;
  const outcome = m.error?.message ?? 'ok';
  console.log(m.operation, m.durationMs, outcome);
});

Other loggers ​

  • Transports. ssh() and tls() take a logger of their own, for what happens while connecting: legacy algorithms enabled, host-key checks disabled, tunnel hops. client.setLogger() doesn't change it.
  • Call home. listenCallHome() takes a logger for the listener. Each client it accepts starts with that logger, and setLogger() on one client changes that client only.
  • nnc. The CLI has its own trace command, which can also show the bytes and frames under each message.

Released under the MIT Licence.