Security News
Cloudflare Adds Security.txt Setup Wizard
Cloudflare has launched a setup wizard allowing users to easily create and manage a security.txt file for vulnerability disclosure on their websites.
Minimal lightweight logging for JavaScript, adding reliable log level methods to any available console.log methods
The loglevel npm package is a minimal lightweight logging library for JavaScript. It provides a simple way to manage logging levels and output logs to the console with an API that is easy to use and extend. It is designed to be a reliable foundation for log management in any JavaScript environment.
Setting log levels
This feature allows you to set the logging level threshold. Messages with a level lower than the threshold will not be output. In this example, the log level is set to DEBUG, which is the lowest level, meaning all logs will be output.
log.setLevel(log.levels.DEBUG);
Logging messages
This feature is used to log messages. The loglevel package provides different methods for different levels of logging, such as log.error for errors. In this example, an error message is logged to the console.
log.error('This is an error message');
Silent logging
This feature allows you to disable all logging, regardless of the current log level. In this example, all logging is disabled, which can be useful in production environments.
log.disableAll();
Enabling logging
This feature allows you to enable all logging, regardless of the current log level. In this example, all logging is enabled, which can be useful during development or debugging.
log.enableAll();
Winston is a multi-transport async logging library for Node.js. It is more feature-rich than loglevel, providing support for multiple storage options, custom log levels, and custom transports, which allows logs to be stored in files, databases, or other services.
Pino is a very low overhead Node.js logger, which focuses on performance. It provides similar functionality to loglevel but is optimized for speed and includes features like child loggers and custom serializers.
Bunyan is a simple and fast JSON logging library for Node.js services. It includes features like log rotation, streams, and more structured log management. It is more complex than loglevel and is designed for use with larger-scale applications.
Minimal lightweight simple logging for JavaScript. loglevel replaces console.log() and friends with level-based logging and filtering, with none of console's downsides.
This is a barebones reliable everyday logging library. It does not do fancy things, it does not let you reconfigure appenders or add complex log filtering rules or boil tea (more's the pity), but it does have the all core functionality that you actually use:
If you're using NPM, you can just run npm install loglevel
.
Alternatively, loglevel is also available via Bower (bower install loglevel
), JamJS (jam install loglevel
), as a Webjar, or an Atmosphere package (for Meteor)
Alternatively if you just want to grab the file yourself, you can download either the current stable production version or the development version directly, or reference it remotely on CDNJS at //cdnjs.cloudflare.com/ajax/libs/loglevel/0.6.0/loglevel.min.js
Finally, if you want to tweak loglevel to your own needs or you immediately need the cutting-edge version, clone this repo and see Developing & Contributing below for build instructions.
loglevel supports AMD (e.g. RequireJS), CommonJS (e.g. Node.js) and direct usage (e.g. loading globally with a <script> tag) loading methods. You should be able to do nearly anything, and then skip to the next section anyway and have it work. Just in case though, here's some specific examples that definitely do the right thing:
var log = require('loglevel');
log.info("unreasonably simple");
define(['loglevel'], function(log) {
log.warn("dangerously convenient");
});
<script src="loglevel.min.js"></script>
<script>
log.error("too easy");
</script>
If you're using another JavaScript library that exposes a 'log' global, you can run into conflicts with loglevel. Similarly to jQuery, you can solve this by putting loglevel into no-conflict mode immediately after it is loaded onto the page. This resets to 'log' global to its value before loglevel was loaded (typically undefined
), and returns the loglevel object, which you can then bind to another name yourself.
For example:
<script src="loglevel.min.js"></script>
<script>
var logging = log.noConflict();
logging.error("still pretty easy");
</script>
The loglevel API is extremely minimal. All methods are available on the root loglevel object, which it's suggested you name 'log' (this is the default if you import it in globally, and is what's set up in the above examples). The API consists of:
5 actual logging methods, ordered and available as:
log.trace(msg)
log.debug(msg)
log.info(msg)
log.warn(msg)
log.error(msg)
Exact output formatting of these will depend on the console available in the current context of your application. Notably, many environments will include a full stack trace with all trace() calls, and icons or similar to highlight other calls.
These methods should never fail in any environment, even if no console object is currently available, and should always fall back to an available log method even if the specific method called (e.g. warn) isn't available.
A log.setLevel(level)
method.
This disables all logging below the given level, so that after a log.setLevel("warn") call log.warn("something") or log.error("something") will output messages, but log.info("something") will not.
This can take either a log level name or 'silent' (which disables everything) in one of a few forms:
Where possible the log level will be persisted. LocalStorage will be used if available, falling back to cookies if not. If neither is available in the current environment (i.e. in Node) persistence will be skipped.
If log.setLevel() is called when a console object is not available (in IE 8 or 9 before the developer tools have been opened, for example) logging will remain silent until the console becomes available, and then begin logging at the requested level.
log.enableAll()
and log.disableAll()
methods.
These enable or disable all log messages, and are equivalent to log.setLevel("trace") and log.setLevel("silent") respectively.
Loglevel provides a simple reliable minimal base for console logging that works everywhere. This means it doesn't include lots of fancy functionality that might be useful in some cases, such as log formatting and redirection (e.g. also sending log messages to a server over AJAX)
Including that would increase the size and complexity of the library, but more importantly would remove stacktrace information. Currently log methods are either disabled, or enabled with directly bound versions of the console.log methods (where possible). This means your browser shows the log message as coming from your code at the call to log.info("message!")
not from within loglevel, since it's really calls the bound console method directly, without indirection. The indirection required to dynamically format, further filter, or redirect log messages would stop this.
There's clearly enough enthusiasm for this even at that cost though that loglevel now includes a plugin API. To use it, redefine log.methodFactory(methodName, logLevel) with a function of your own. This will be called for each enabled method each time the level is set (including initially), and should return a function to be used for the given log method, at the given level. If you'd like to retain all the reliability and features of loglevel, it's recommended that this wraps the initially provided value of log.methodFactory
For example, a plugin to prefix all log messages with "Newsflash: " would look like:
var originalFactory = log.methodFactory;
log.methodFactory = function (methodName, logLevel) {
var rawMethod = originalFactory(methodName, logLevel);
return function (message) {
rawMethod("Newsflash: " + message);
};
};
If you develop and release a plugin, please get in contact! I'd be happy to reference it here for future users. Some consistency is helpful; naming your plugin 'loglevel-PLUGINNAME' (e.g. loglevel-newsflash) is preferred, as is giving it the 'loglevel-plugin' keyword in your package.json
In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality.
Builds can be run with grunt: run grunt dist
to build a distributable version of the project (in /dist), or grunt test
to just run the tests and linting. During development you can run grunt watch
and it will monitor source files, and rerun the tests and linting as appropriate when they're changed.
Also, please don't manually edit files in the "dist" subdirectory as they are generated via Grunt. You'll find source code in the "lib" subdirectory!
To do a release of loglevel:
grunt dist
to build a distributable version in dist/npm publish .
to publish to NPMjam publish
to publish to JamJSv0.1.0 - First working release with apparent compatibility with everything tested
v0.2.0 - Updated release with various tweaks and polish and real proper documentation attached
v0.3.0 - Some bugfixes (#12, #14), cookie-based log level persistence, doc tweaks, support for Bower and JamJS
v0.3.1 - Fixed incorrect text in release build banner, various other minor tweaks
v0.4.0 - Use LocalStorage for level persistence if available, compatibility improvements for IE, improved error messages, multi-environment tests
v0.5.0 - Fix for Modernizr+IE8 issues, improved setLevel error handling, support for auto-activation of desired logging when console eventually turns up in IE8
v0.6.0 - Handle logging in Safari private browsing mode (#33), fix TRACE level persistence bug (#35), plus various minor tweaks
v1.0.0 - Official stable release! Fixed a bug with localStorage in Android webviews, improved CommonJS detection, and added noConflict().
v1.1.0 - Added support for including loglevel with preprocessing and .apply() (#50), and fixed QUnit dep version which made tests potentially unstable.
v1.2.0 - New plugin API! Plus various bits of refactoring and tidy up, nicely simplifying things and trimming the size down.
Copyright (c) 2013 Tim Perry
Licensed under the MIT license.
FAQs
Minimal lightweight logging for JavaScript, adding reliable log level methods to any available console.log methods
The npm package loglevel receives a total of 6,766,464 weekly downloads. As such, loglevel popularity was classified as popular.
We found that loglevel demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Cloudflare has launched a setup wizard allowing users to easily create and manage a security.txt file for vulnerability disclosure on their websites.
Security News
The Socket Research team breaks down a malicious npm package targeting the legitimate DOMPurify library. It uses obfuscated code to hide that it is exfiltrating browser and crypto wallet data.
Security News
ENISA’s 2024 report highlights the EU’s top cybersecurity threats, including rising DDoS attacks, ransomware, supply chain vulnerabilities, and weaponized AI.