Gathering detailed insights and metrics for diagnostics
Gathering detailed insights and metrics for diagnostics
Gathering detailed insights and metrics for diagnostics
Gathering detailed insights and metrics for diagnostics
npm install diagnostics
94.2
Supply Chain
99
Quality
78.6
Maintenance
100
Vulnerability
100
License
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
35 Stars
63 Commits
11 Forks
6 Watching
1 Branches
4 Contributors
Updated on 19 Aug 2024
Minified
Minified + Gzipped
JavaScript (100%)
Cumulative downloads
Total Downloads
Last day
-26.7%
91,421
Compared to previous day
Last week
-9.3%
674,149
Compared to previous week
Last month
27.8%
3,095,246
Compared to previous month
Last year
-53.5%
43,627,664
Compared to previous year
diagnostics
Diagnostics in the evolution of debug pattern that is used in the Node.js core,
this extremely small but powerful technique can best be compared as feature
flags for loggers. The created debug logger is disabled by default but can be
enabled without changing a line of code, using flags.
The module is released in the public npm registry and can be installed by running:
npm install --save diagnostics
To create a new logger simply require
the diagnostics
module and call
the returned function. It accepts 2 arguments:
namespace
Required This is the namespace of your logger so we know if we need to
enable your logger when a debug flag is used. Generally you use the name of
your library or application as first root namespace. For example if you're
building a parser in a library (example) you would set namespace
example:parser
.options
An object with additional configuration for the logger.
following keys are recognized:
force
Force the logger to be enabled.colors
Colors are enabled by default for the logs, but you can set this
option to false
to disable it.1const debug = require('diagnostics')('foo:bar:baz'); 2const debug = require('diagnostics')('foo:bar:baz', { options }); 3 4debug('this is a log message %s', 'that will only show up when enabled'); 5debug('that is pretty neat', { log: 'more', data: 1337 });
Unlike console.log
statements that add and remove during your development
lifecycle you create meaningful log statements that will give you insight in
the library or application that you're developing.
The created debugger uses different "adapters" to extract the debug flag out of the JavaScript environment. To learn more about enabling the debug flag in your specific environment click on one of the enabled adapters below.
Please note that the returned logger is fully configured out of the box, you do not need to set any of the adapters/modifiers your self, they are there for when you want more advanced control over the process. But if you want to learn more about that, read the next section.
There are 2 specific usage patterns for diagnostic
, library developers who
implement it as part of their modules and applications developers who either
use it in their application or are searching for ways to consume the messages.
With the simple log interface as discussed in the introduction section we make it easy for developers to add it as part of their libraries and applications, and with powerful API we allow infinite customization by allowing custom adapters, loggers and modifiers to ensure that this library maintains relevant. These methods not only allow introduction of new loggers, but allow you think outside the box. For example you can maintain a history of past log messages, and output those when an uncaught exception happens in your application so you have additional context
1const diagnostics = require('diagnostics'); 2 3let index = 0; 4const limit = 200; 5const history = new Array(limit); 6 7// 8// Force all `diagnostic` loggers to be enabled. 9// 10diagnostics.force = process.env.NODE_ENV === 'prod'; 11diagnostics.set(function customLogger(meta, message) { 12 history[index]= { meta, message, now: Date.now() }; 13 if (index++ === limit) index = 0; 14 15 // 16 // We're running a development build, so output. 17 // 18 if (meta.dev) console.log.apply(console, message); 19}); 20 21process.on('uncaughtException', async function (err) { 22 await saveErrorToDisk(err, history); 23 process.exit(1); 24});
The small snippet above will maintain a 200 limited FIFO (First In First Out) queue of all debug messages that can be referenced when your application crashes
When you require
the diagnostics
module you will be given a logger that is
optimized for development
so it can provide the best developer experience
possible.
The development logger enables all the adapters for your
JavaScript environment, adds a logger that outputs the messages to console.log
and registers our message modifiers so log messages will be prefixed with the
supplied namespace so you know where the log messages originates from.
The development logger does not have any adapter, modifier and logger enabled
by default. This ensures that your log messages never accidentally show up in
production. However this does not mean that it's not possible to get debug
messages in production. You can force
the debugger to be enabled, and
supply a custom logger.
1const diagnostics = require('diagnostics'); 2const debug = debug('foo:bar', { force: true }); 3 4// 5// Or enable _every_ diagnostic instance: 6// 7diagnostics.force = true;
WebPack has the concept of mode's which creates different
1module.exports = { 2 mode: 'development' // 'production' 3}
When you are building your app using the WebPack CLI you can use the --mode
flag:
webpack --mode=production app.js -o /dist/bundle.js
When you are running your app using Node.js
you should the NODE_ENV
environment variable to production
to ensure that you libraries that you
import are optimized for production.
NODE_ENV=production node app.js
The returned logger exposes some addition properties that can be used used in your application or library:
The returned logger will have a .enabled
property assigned to it. This boolean
can be used to check if the logger was enabled:
1const debug = require('diagnostics')('foo:bar'); 2 3if (debug.enabled) { 4 // 5 // Do something special 6 // 7}
This property is exposed as:
This is the namespace that you originally provided to the function.
1const debug = require('diagnostics')('foo:bar'); 2 3console.log(debug.namespace); // foo:bar
This property is exposed as:
There are different builds available of diagnostics
, when you create a
production build of your application using NODE_ENV=production
you will be
given an optimized, smaller build of diagnostics
to reduce your bundle size.
The dev
and prod
booleans on the returned logger indicate if you have a
production or development version of the logger.
1const debug = require('diagnostics')('foo:bar'); 2 3if (debug.prod) { 4 // do stuff 5}
This property is exposed as:
Sets a new logger as default for all diagnostic
instances. The passed
argument should be a function that write the log messages to where ever you
want. It receives 2 arguments:
meta
An object with all the options that was provided to the original
logger that wants to write the log message as well as properties of the
debugger such as prod
, dev
, namespace
, enabled
. See API for
all exposed properties.args
An array of the log messages that needs to be written.1const debug = require('diagnostics')('foo:more:namespaces'); 2 3debug.use(function logger(meta, args) { 4 console.log(meta); 5 console.debug(...args); 6});
This method is exposed as:
diagnostics
module.The modify method allows you add a new message modifier to all diagnostic
instances. The passed argument should be a function that returns the passed
message after modification. The function receives 2 arguments:
message
, Array, the log message.options
, Object, the options that were passed into the logger when it was
initially created.1const debug = require('diagnostics')('example:modifiers'); 2 3debug.modify(function (message, options) { 4 return messages; 5});
This method is exposed as:
diagnostics
module.See modifiers for more information.
Adds a new adapter
to all diagnostic
instances. The passed argument
should be a function returns a boolean that indicates if the passed in
namespace
is allowed to write log messages.
1const diagnostics = require('diagnostics'); 2const debug = diagnostics('foo:bar'); 3 4debug.use(function (namespace) { 5 return namespace === 'foo:bar'; 6});
This method is exposed as:
diagnostics
module.See adapters for more information.
To be as flexible as possible when it comes to transforming messages we've
come up with the concept of modifiers
which can enhance the debug messages.
This allows you to introduce functionality or details that you find important
for debug messages, and doesn't require us to add additional bloat to the
diagnostic
core.
For example, you want the messages to be prefixed with the date-time of when the log message occured:
1const diagnostics = require('diagnostics'); 2 3diagnostics.modify(function datetime(args, options) { 4 args.unshift(new Date()); 5 return args; 6});
Now all messages will be prefixed with date that is outputted by new Date()
.
The following modifiers are shipped with diagnostics
and are enabled in
development mode only:
This modifier is enabled for all debug instances and prefixes the messages
with the name of namespace under which it is logged. The namespace is colored
using the colorspace
module which groups similar namespaces under the same
colorspace. You can have multiple namespaces for the debuggers where each
namespace should be separated by a :
foo
foo:bar
foo:bar:baz
For console based output the namespace-ansi
is used.
Adapters allows diagnostics
to pull the DEBUG
and DIAGNOSTICS
environment
variables from different sources. Not every JavaScript environment has a
process.env
that we can leverage. Adapters allows us to have different
adapters for different environments. It means you can write your own custom
adapter if needed as well.
The adapter
function should be passed a function as argument, this function
will receive the namespace
of a logger as argument and it should return a
boolean that indicates if that logger should be enabled or not.
1const debug = require('diagnostics')('example:namespace'); 2 3debug.adapter(require('diagnostics/adapters/localstorage'));
The modifiers are only enabled for development
. The following adapters are
available are available:
This adapter is enabled for node.js
.
Uses the DEBUG
or DIAGNOSTICS
(both are recognized) environment variables to
pass in debug flag:
UNIX/Linux/Mac
DEBUG=foo* node index.js
Using environment variables on Windows is a bit different, and also depends on toolchain you are using:
Windows
set DEBUG=foo* & node index.js
Powershell
$env:DEBUG='foo*';node index.js
This adapter is enabled for browsers
.
This adapter uses the window.location.hash
of as source for the environment
variables. It assumes that hash is formatted using the same syntax as query
strings:
1http://example.com/foo/bar#debug=foo*
It triggers on both the debug=
and diagnostics=
names.
This adapter is enabled for browsers
.
This adapter uses the localStorage
of the browser to store the debug flags.
You can set the debug flag your self in your application code, but you can
also open browser WebInspector and enable it through the console.
1localStorage.setItem('debug', 'foo*');
It triggers on both the debug
and diagnostics
storage items. (Please note
that these keys should be entered in lowercase)
This adapter is enabled for react-native
.
This adapter uses the AsyncStorage
API that is exposed by the react-native
library to store and read the debug
or diagnostics
storage items.
1import { AsyncStorage } from 'react-native'; 2 3AsyncStorage.setItem('debug', 'foo*');
Unlike other adapters, this is the only adapter that is async
so that means
that we're not able to instantly determine if a created logger should be
enabled or disabled. So when a logger is created in react-native
we initially
assume it's disabled, any message that send during period will be queued
internally.
Once we've received the data from the AsyncStorage
API we will determine
if the logger should be enabled, flush the queued messages if needed and set
all enabled
properties accordingly on the returned logger.
By default it will log all messages to console.log
in when the logger is
enabled using the debug flag that is set using one of the adapters.
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
0 existing vulnerabilities detected
Reason
Found 2/21 approved changesets -- score normalized to 0
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More