loglevel-1.7.1/ 0000775 0000000 0000000 00000000000 13757442753 0013352 5 ustar 00root root 0000000 0000000 loglevel-1.7.1/.editorconfig 0000664 0000000 0000000 00000000603 13757442753 0016026 0 ustar 00root root 0000000 0000000
# EditorConfig defines and maintains consistent coding styles between different
# editors and IDEs: http://EditorConfig.org/
# Top-most EditorConfig file
root = true
# All files
[*.*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 4
trim_trailing_whitespace = true
max_line_length = 80
[*.md]
indent_size = 2
[*.json]
indent_size = 2
loglevel-1.7.1/.github/ 0000775 0000000 0000000 00000000000 13757442753 0014712 5 ustar 00root root 0000000 0000000 loglevel-1.7.1/.github/FUNDING.yml 0000664 0000000 0000000 00000000031 13757442753 0016521 0 ustar 00root root 0000000 0000000 tidelift: "npm/loglevel"
loglevel-1.7.1/.gitignore 0000664 0000000 0000000 00000000245 13757442753 0015343 0 ustar 00root root 0000000 0000000 /node_modules/
/coverage
/.idea/
*.swp
*.sublime*
lib-cov
*.seed
*.log
*.csv
*.dat
*.out
*.pid
*.gz
pids
logs
results
npm-debug.log
*.iml
_SpecRunner.html
.grunt
loglevel-1.7.1/.jshintrc 0000664 0000000 0000000 00000000322 13757442753 0015174 0 ustar 00root root 0000000 0000000 {
"curly": false,
"eqeqeq": true,
"immed": true,
"latedef": true,
"newcap": true,
"noarg": true,
"sub": true,
"undef": true,
"unused": true,
"boss": true,
"eqnull": true,
"node": true
}
loglevel-1.7.1/.travis.yml 0000664 0000000 0000000 00000000353 13757442753 0015464 0 ustar 00root root 0000000 0000000 language: node_js
node_js:
# - "12" Doesn't work yet - requires Jasmine updates/replacement
# - "10" Doesn't work yet - requires Jasmine updates/replacement
- "8"
- "6"
- "4"
- "0.12"
- "0.10"
script: "npm run-script ci"
loglevel-1.7.1/CONTRIBUTING.md 0000664 0000000 0000000 00000007557 13757442753 0015621 0 ustar 00root root 0000000 0000000 Filing tickets against loglevel
===============================
If you'd like to file a bug or a feature request for loglevel, the best option is to [open an issue on Github](https://github.com/pimterry/loglevel/issues/new).
If you're filing a feature request, please remember:
* Feature requests significantly expanding the scope of loglevel outside the description in [the readme](https://github.com/pimterry/loglevel/blob/master/README.md) will probably be rejected.
* Features that can't be meaningfully implemented in a cross-environment compatible manner won't be implemented.
* Please check the previously opened issues to see if somebody else has suggested it first.
* Consider submitting a pull request to add the feature instead, if you're confident it fits within the above
If you're filing a bug, please remember:
* To provide detailed steps to reproduce the behaviour
* If possible, provide a Jasmine test which reproduces the behaviour
* Please specify the exact details of the environment in which it fails: OS + Environment (i.e. Browser or Node) + version
* Consider submitting a pull request to fix the bug instead
Helping develop loglevel
================================
If you'd like to help develop loglevel further, please submit a pull request! I'm very keen to improve loglevel further, and good pull requests will be enthusiastically merged.
Before submitting a pull request to fix a bug or add a new feature, please check the lists above to ensure it'll be accepted. Browser compatibility is particularly important here; if you add a feature or fix a bug which breaks things on other browsers it will not be merged, no matter how awesome it may be.
To be more specific, before submitting your pull request please ensure:
* You haven't broken the existing test suite in any obvious browsers (at least check latest IE/FF/Chrome - automatic saucelabs tests for this are coming soon too)
* You've added relevant tests for the bug you're fixing/the new feature you're adding/etc, which pass in all the relevant browsers
* JSHint is happy with your new code
* You've updated the API docs (in README.md) to detail any changes you've made to the public interface
* Your change is backward compatible (or you've explicitly said if it's not; this isn't great, but will be considered)
* You haven't changed any files in dist/ (these are auto-generated, and should only be changed on release)
Project structure
-----------------
The core project code is all in lib/loglevel.js, and this should be the only file you need to touch for functional changes themselves.
The released code is in dist/*.js, and should not be touched by anything except releases
The test suite is entirely in test/*.js:
* Every file ending in '-test.js' is a unit test, is written in RequireJS, and should pass in any environment
* global-integration.js and node-integration.js are quick integration smoke tests for node and for browser global usage
* test-helpers.js contains some test utilities
* manual-test.html is a test page which includes the current loglevel build, so you can manually check it works in a given browser
How to make your change and submit it
-------------------------------------
1. Fork loglevel
2. Clone your fork locally
3. Create a branch from master for your change
4. Write some tests in /test for your change, as relevant
5. Make your code changes in /lib/loglevel.js
6. Check your code all passes (run `grunt`) - if you have any issues try running `grunt jasmine:requirejs:src:build` (or a different test build instead of 'requirejs': see the jasmine config in Gruntfile.js) and debugging the generated _SpecRunner.html in a browser
7. Commit your changes
8. Open a pull request back to master in loglevel
Reporting security issues
-------------------------
Tidelift acts as the security contact for loglevel. Issues can be reported to security@tidelift.com, see https://tidelift.com/security for more details.
loglevel-1.7.1/Gruntfile.js 0000664 0000000 0000000 00000021120 13757442753 0015643 0 ustar 00root root 0000000 0000000 'use strict';
module.exports = function (grunt) {
// Project configuration.
grunt.initConfig({
// Metadata.
pkg: grunt.file.readJSON('package.json'),
banner: '/*! <%= pkg.name %> - v<%= pkg.version %>' +
' - <%= pkg.homepage %>' +
' - (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>' +
' - licensed <%= pkg.license %> */\n',
// Task configuration.
concat: {
options: {
banner: '<%= banner %>',
stripBanners: true
},
dist: {
src: ['lib/<%= pkg.name %>.js'],
dest: 'dist/<%= pkg.name %>.js'
}
},
uglify: {
options: {
banner: '<%= banner %>'
},
dist: {
src: '<%= concat.dist.dest %>',
dest: 'dist/<%= pkg.name %>.min.js'
}
},
jasmine: {
requirejs: {
src: [],
options: {
specs: 'test/*-test.js',
vendor: 'test/vendor/*.js',
helpers: 'test/*-helper.js',
template: require('grunt-template-jasmine-requirejs')
}
},
global: {
src: 'lib/**/*.js',
options: {
specs: 'test/global-integration.js',
vendor: 'test/vendor/*.js'
}
},
context: {
src: 'test/test-context-using-apply.generated.js',
options: {
specs: 'test/global-integration-with-new-context.js',
vendor: 'test/vendor/*.js'
}
},
withCoverage: {
src: 'lib/**/*.js',
options: {
specs: 'test/*-test.js',
vendor: 'test/vendor/*.js',
helpers: 'test/*-helper.js',
template: require('grunt-template-jasmine-istanbul'),
templateOptions: {
coverage: 'coverage/coverage.json',
report: [
{
type: 'html',
options: {
dir: 'coverage'
}
},
{
type: 'lcov',
options: {
dir: 'coverage'
}
}
],
template: require('grunt-template-jasmine-requirejs'),
templateOptions: {
requireConfig: {
paths: {
"lib": '.grunt/grunt-contrib-jasmine/lib/'
}
}
}
}
}
}
},
"jasmine_node": {
test: {
options: {
match: "node-integration.",
matchall: true,
projectRoot: "./test",
useHelpers: false
}
}
},
coveralls: {
src: 'coverage/lcov.info'
},
open: {
jasmine: {
path: 'http://127.0.0.1:8000/_SpecRunner.html'
}
},
connect: {
test: {
port: 8000,
keepalive: true
}
},
'saucelabs-jasmine': {
// Requires valid SAUCE_USERNAME and SAUCE_ACCESS_KEY in env to run.
all: {
options: {
urls: ['http://localhost:8000/_SpecRunner.html'],
browsers: [
{"browserName": "firefox", "platform": "Windows 2003", "version": "3.6"},
{"browserName": "firefox", "platform": "Windows 2003", "version": "4"},
{"browserName": "firefox", "platform": "Windows 2003", "version": "25"},
{"browserName": "safari", "platform": "Mac 10.6", "version": "5"},
{"browserName": "safari", "platform": "Mac 10.8", "version": "6"},
{"browserName": "googlechrome", "platform": "Windows 7"},
{"browserName": "opera", "platform": "Windows 2003", "version": "12"},
// Disabled because old IE breaks the Jasmine runner; these have to be manually tested
// {"browserName": "iehta", "platform": "Windows XP", "version": "6"},
// {"browserName": "iehta", "platform": "Windows XP", "version": "7"},
// {"browserName": "iehta", "platform": "Windows XP", "version": "8"},
{"browserName": "iehta", "platform": "Windows 7", "version": "9"},
{"browserName": "iehta", "platform": "Windows 7", "version": "10"},
{"browserName": "opera", "platform": "Windows 7", "version": "12"},
{"browserName": "android", "platform": "Linux", "version": "4.0"},
{"browserName": "iphone", "platform": "OS X 10.8", "version": "6"}
],
concurrency: 3,
detailedError: true,
testTimeout:10000,
testInterval:1000,
testReadyTimeout:2000,
testname: 'loglevel jasmine test',
tags: [process.env.TRAVIS_REPO_SLUG || "local", process.env.TRAVIS_COMMIT || "manual"]
}
}
},
jshint: {
options: {
jshintrc: '.jshintrc'
},
gruntfile: {
src: 'Gruntfile.js'
},
lib: {
options: {
jshintrc: 'lib/.jshintrc'
},
src: ['lib/**/*.js']
},
test: {
options: {
jshintrc: 'test/.jshintrc'
},
src: ['test/*.js', '!test/*.generated.js']
}
},
watch: {
gruntfile: {
files: '<%= jshint.gruntfile.src %>',
tasks: ['jshint:gruntfile']
},
lib: {
files: '<%= jshint.lib.src %>',
tasks: ['jshint:lib', 'test']
},
test: {
files: '<%= jshint.test.src %>',
tasks: ['jshint:test', 'test']
}
},
qunit: {
all: ['test/*-qunit.html']
},
preprocess: {
"test-context-using-apply": {
src: 'test/test-context-using-apply.js',
dest: 'test/test-context-using-apply.generated.js'
}
},
clean:{
test:['test/test-context-using-apply.generated.js']
}
});
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-jasmine');
grunt.loadNpmTasks('grunt-coveralls');
grunt.loadNpmTasks('grunt-jasmine-node');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-qunit');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-open');
grunt.loadNpmTasks('grunt-saucelabs');
grunt.loadNpmTasks('grunt-preprocess');
grunt.loadNpmTasks('grunt-contrib-clean');
// Build a distributable release
grunt.registerTask('dist', ['test', 'concat', 'uglify']);
// Check everything is good
grunt.registerTask('test', ['jshint', 'jasmine:requirejs', 'jasmine:global', 'preprocess', 'jasmine:context', 'clean:test', 'jasmine_node', 'jasmine:withCoverage', 'qunit']);
// Test with a live server and an actual browser
grunt.registerTask('integration-test', ['jasmine:requirejs:src:build', 'open:jasmine', 'connect:test:keepalive']);
// Test with lots of browsers on saucelabs. Requires valid SAUCE_USERNAME and SAUCE_ACCESS_KEY in env to run.
grunt.registerTask('saucelabs', ['jasmine:requirejs:src:build', 'connect:test', 'saucelabs-jasmine']);
// Default task.
grunt.registerTask('default', 'test');
grunt.registerTask('ci', ['test', 'coveralls']);
};
loglevel-1.7.1/LICENSE-MIT 0000664 0000000 0000000 00000002035 13757442753 0015006 0 ustar 00root root 0000000 0000000 Copyright (c) 2013 Tim Perry
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
loglevel-1.7.1/README.md 0000664 0000000 0000000 00000054044 13757442753 0014640 0 ustar 00root root 0000000 0000000
# loglevel [![NPM version][npm-image]][npm-url] [](https://www.npmjs.com/package/loglevel) [](https://travis-ci.org/pimterry/loglevel) [](https://coveralls.io/r/pimterry/loglevel?branch=master)
[npm-image]: https://img.shields.io/npm/v/loglevel.svg?style=flat
[npm-url]: https://npmjs.org/package/loglevel
> _Don't debug with logs alone - check out [HTTP Toolkit](https://httptoolkit.tech/javascript): beautiful, powerful & open-source tools for building, testing & debugging HTTP(S)_
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:
## Features
### Simple
* Log things at a given level (trace/debug/info/warn/error) to the console object (as seen in all modern browsers & node.js)
* Filter logging by level (all the above or 'silent'), so you can disable all but error logging in production, and then run log.setLevel("trace") in your console to turn it all back on for a furious debugging session
* Single file, no dependencies, weighs in at 1.1KB minified and gzipped
### Effective
* Log methods gracefully fall back to simpler console logging methods if more specific ones aren't available: so calls to log.debug() go to console.debug() if possible, or console.log() if not
* Logging calls still succeed even if there's no console object at all, so your site doesn't break when people visit with old browsers that don't support the console object (here's looking at you IE) and similar
* This then comes together giving a consistent reliable API that works in every JavaScript environment with a console available, and never breaks anything anywhere else
### Convenient
* Log output keeps line numbers: most JS logging frameworks call console.log methods through wrapper functions, clobbering your stacktrace and making the extra info many browsers provide useless. We'll have none of that thanks.
* It works with all the standard JavaScript loading systems out of the box (CommonJS, AMD, or just as a global)
* Logging is filtered to "warn" level by default, to keep your live site clean in normal usage (or you can trivially re-enable everything with an initial log.enableAll() call)
* Magically handles situations where console logging is not initially available (IE8/9), and automatically enables logging as soon as it does become available (when developer console is opened)
* TypeScript type definitions included, so no need for extra `@types` packages
* Extensible, to add other log redirection, filtering, or formatting functionality, while keeping all the above (except you will clobber your stacktrace, see Plugins below)
## Downloading loglevel
If you're using NPM, you can just run `npm install loglevel`.
Alternatively, loglevel is also available via [Bower](https://github.com/bower/bower) (`bower install loglevel`), as a [Webjar](http://www.webjars.org/), or an [Atmosphere package](https://atmospherejs.com/spacejamio/loglevel) (for Meteor)
Alternatively if you just want to grab the file yourself, you can download either the current stable [production version][min] or the [development version][max] directly, or reference it remotely on unpkg at [`https://unpkg.com/loglevel/dist/loglevel.min.js`][cdn] (this will redirect to a latest version, use the resulting redirected URL if you want to pin that version).
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](#developing--contributing) below for build instructions.
[min]: https://raw.github.com/pimterry/loglevel/master/dist/loglevel.min.js
[max]: https://raw.github.com/pimterry/loglevel/master/dist/loglevel.js
[cdn]: https://unpkg.com/loglevel/dist/loglevel.min.js
## Setting it up
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:
### CommonsJS (e.g. Node)
```javascript
var log = require('loglevel');
log.warn("unreasonably simple");
```
### AMD (e.g. RequireJS)
```javascript
define(['loglevel'], function(log) {
log.warn("dangerously convenient");
});
```
### Directly in your web page:
```html
```
### As an ES6 module:
loglevel is written as a UMD module, with a single object exported. Unfortunately ES6 module loaders & transpilers don't all handle this the same way. Some will treat the object as the default export, while others use it as the root exported object. In addition, loglevel includes `default` property on the root object, designed to help handle this differences. Nonetheless, there's two possible syntaxes that might work for you:
For most tools, using the default import is the most convenient and flexible option:
```javascript
import log from 'loglevel';
log.warn("module-tastic");
```
For some tools though, it might better to wildcard import the whole object:
```javascript
import * as log from 'loglevel';
log.warn("module-tastic");
```
There's no major difference, unless you're using TypeScript & building a loglevel plugin (in that case, see https://github.com/pimterry/loglevel/issues/149). In general though, just use whichever suits your environment, and everything should work out fine.
### With noConflict():
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:
```html
```
### TypeScript:
loglevel includes its own type definitions, assuming you're using a modern module environment (e.g. Node.JS, webpack, etc), you should be able to use the ES6 syntax above, and everything will work immediately. If not, file a bug!
If you really want to use LogLevel as a global however, but from TypeScript, you'll need to declare it as such first. To do that:
* Create a `loglevel.d.ts` file
* Ensure that file is included in your build (e.g. add it to `include` in your tsconfig, pass it on the command line, or use `///`)
* In that file, add:
```typescript
import * as log from 'loglevel';
export as namespace log;
export = log;
```
## Documentation
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)`
`log.log(msg)` is also available, as an alias for `log.debug(msg)`, to improve compatibility with `console`, and make migration easier.
Exact output formatting of these will depend on the console available in the current context of your application. For example, 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.
Be aware that all this means that these method won't necessarily always produce exactly the output you expect in every environment; loglevel only guarantees that these methods will never explode on you, and that it will call the most relevant method it can find, with your argument. For example, `log.trace(msg)` in Firefox before version 64 prints the stacktrace by itself, and doesn't include your message (see [#84](https://github.com/pimterry/loglevel/issues/84)).
* A `log.setLevel(level, [persist])` 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:
* As a log level from the internal levels list, e.g. log.levels.SILENT ← _for type safety_
* As a string, like 'error' (case-insensitive) ← _for a reasonable practical balance_
* As a numeric index from 0 (trace) to 5 (silent) ← _deliciously terse, and more easily programmable (...although, why?)_
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), or if you pass `false` as the optional 'persist' second argument, 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.
* A `log.setDefaultLevel(level)` method.
This sets the current log level only if one has not been persisted and can’t be loaded. This is useful when initializing scripts; if a developer or user has previously called `setLevel()`, this won’t alter their settings. For example, your application might set the log level to `error` in a production environment, but when debugging an issue, you might call `setLevel("trace")` on the console to see all the logs. If that `error` setting was set using `setDefaultLevel()`, it will still stay as `trace` on subsequent page loads and refreshes instead of resetting to `error`.
The `level` argument takes is the same values that you might pass to `setLevel()`. Levels set using `setDefaultLevel()` never persist to subsequent page loads.
* `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.
* A `log.getLevel()` method.
Returns the current logging level, as a number from 0 (trace) to 5 (silent)
It's very unlikely you'll need to use this for normal application logging; it's provided partly to help plugin development, and partly to let you optimize logging code as below, where debug data is only generated if the level is set such that it'll actually be logged. This probably doesn't affect you, unless you've run profiling on your code and you have hard numbers telling you that your log data generation is a real performance problem.
```javascript
if (log.getLevel() <= log.levels.DEBUG) {
var logData = runExpensiveDataGeneration();
log.debug(logData);
}
```
This notably isn't the right solution to avoid the cost of string concatenation in your logging. Firstly, it's very unlikely that string concatenation in your logging is really an important performance problem. Even if you do genuinely have hard metrics showing that it is though, the better solution that wrapping your log statements in this is to use multiple arguments, as below. The underlying console API will automatically concatenate these for you if logging is enabled, and if it isn't then all log methods are no-ops, and no concatenation will be done at all.
```javascript
// Prints 'My concatenated log message'
log.debug("My ", "concatenated ", "log message");
```
* A `log.getLogger(loggerName)` method.
This gets you a new logger object that works exactly like the root `log` object, but can have its level and logging methods set independently. All loggers must have a name (which is a non-empty string, or a [Symbol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol)). Calling `getLogger()` multiple times with the same name will return an identical logger object.
In large applications, it can be incredibly useful to turn logging on and off for particular modules as you are working with them. Using the `getLogger()` method lets you create a separate logger for each part of your application with its own logging level.
Likewise, for small, independent modules, using a named logger instead of the default root logger allows developers using your module to selectively turn on deep, trace-level logging when trying to debug problems, while logging only errors or silencing logging altogether under normal circumstances.
Example usage *(using CommonJS modules, but you could do the same with any module system):*
```javascript
// In module-one.js:
var log = require("loglevel").getLogger("module-one");
function doSomethingAmazing() {
log.debug("Amazing message from module one.");
}
// In module-two.js:
var log = require("loglevel").getLogger("module-two");
function doSomethingSpecial() {
log.debug("Special message from module two.");
}
// In your main application module:
var log = require("loglevel");
var moduleOne = require("module-one");
var moduleTwo = require("module-two");
log.getLogger("module-two").setLevel("TRACE");
moduleOne.doSomethingAmazing();
moduleTwo.doSomethingSpecial();
// logs "Special message from module two."
// (but nothing from module one.)
```
Loggers returned by `getLogger()` support all the same properties and methods as the default root logger, excepting `noConflict()` and the `getLogger()` method itself.
Like the root logger, other loggers can have their logging level saved. If a logger’s level has not been saved, it will inherit the root logger’s level when it is first created. If the root logger’s level changes later, the new level will not affect other loggers that have already been created. Loggers with Symbol names (rather than string names) will be always considered as unique instances, and will never have their logging level saved or restored.
Likewise, loggers will inherit the root logger’s `methodFactory`. After creation, each logger can have its `methodFactory` independently set. See the *plugins* section below for more about `methodFactory`.
* A `log.getLoggers()` method.
This will return you the dictionary of all loggers created with `getLogger`, keyed off of their names.
## Plugins
### Existing plugins:
[loglevel-plugin-prefix](https://github.com/kutuluk/loglevel-plugin-prefix) - plugin for loglevel message prefixing.
[loglevel-plugin-remote](https://github.com/kutuluk/loglevel-plugin-remote) - plugin for sending loglevel messages to a remote log server.
ServerSend - https://github.com/artemyarulin/loglevel-serverSend - Forward your log messages to a remote server.
DEBUG - https://github.com/vectrlabs/loglevel-debug - Control logging from a DEBUG environmental variable (similar to the classic [Debug](https://github.com/visionmedia/debug) module)
### Writing plugins:
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 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, loggerName) 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, for a logger with the given name. 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:
```javascript
var originalFactory = log.methodFactory;
log.methodFactory = function (methodName, logLevel, loggerName) {
var rawMethod = originalFactory(methodName, logLevel, loggerName);
return function (message) {
rawMethod("Newsflash: " + message);
};
};
log.setLevel(log.getLevel()); // Be sure to call setLevel method in order to apply plugin
```
*(The above supports only a single log.warn("") argument for clarity, but it's easy to extend to a [fuller variadic version](http://jsbin.com/xehoye/edit?html,console))*
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
## Developing & Contributing
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 npm: run `npm run dist` to build a distributable version of the project (in /dist), or `npm test` to just run the tests and linting. During development you can run `npm run 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!_
#### Release process
To do a release of loglevel:
* Update the version number in package.json and bower.json
* Run `npm run dist` to build a distributable version in dist/
* Update the release history in this file (below)
* Commit the built code, tagging it with the version number and a brief message about the release
* Push to Github
* Run `npm publish .` to publish to NPM
## Release History
v0.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.
v1.3.0 - Make persistence optional in setLevel, plus lots of documentation updates and other small tweaks
v1.3.1 - With the new optional persistence, stop unnecessarily persisting the initially set default level (warn)
v1.4.0 - Add getLevel(), setDefaultLevel() and getLogger() functionality for more fine-grained log level control
v1.4.1 - Reorder UMD (#92) to improve bundling tool compatibility
v1.5.0 - Fix log.debug (#111) after V8 changes deprecating console.debug, check for `window` upfront (#104), and add `.log` alias for `.debug` (#64)
v1.5.1 - Fix bug (#112) in level-persistence cookie fallback, which failed if it wasn't the first cookie present
v1.6.0 - Add a name property to loggers and add log.getLoggers() (#114), and recommend unpkg as CDN instead of CDNJS.
v1.6.1 - Various small documentation & test updates
v1.6.2 - Include TypeScript type definitions in the package itself
v1.6.3 - Avoid TypeScript type conflicts with other global `log` types (e.g. `core-js`)
v1.6.4 - Ensure package.json's 'main' is a fully qualified path, to fix webpack issues
v1.6.5 - Ensure the provided message is included when calling trace() in IE11
v1.6.6 - Fix bugs in v1.6.5, which caused issues in node.js & IE < 9
v1.6.7 - Fix a bug in environments with `window` defined but no `window.navigator`
v1.6.8 - Update TypeScript type definitions to include `log.log()`.
v1.7.0 - Add support for Symbol-named loggers, and a `.default` property to help with ES6 module usage.
v1.7.1 - Update TypeScript types to support Symbol-named loggers.
## `loglevel` for enterprise
Available as part of the Tidelift Subscription.
The maintainers of `loglevel` and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-loglevel?utm_source=npm-loglevel&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
## License
Copyright (c) 2013 Tim Perry
Licensed under the MIT license.
loglevel-1.7.1/_config.yml 0000664 0000000 0000000 00000000033 13757442753 0015475 0 ustar 00root root 0000000 0000000 theme: jekyll-theme-minimal loglevel-1.7.1/bower.json 0000664 0000000 0000000 00000000254 13757442753 0015364 0 ustar 00root root 0000000 0000000 {
"name": "loglevel",
"version": "1.7.1",
"main": "dist/loglevel.min.js",
"dependencies": {},
"ignore": [
"**/.*",
"node_modules",
"components"
]
}
loglevel-1.7.1/index.d.ts 0000664 0000000 0000000 00000020310 13757442753 0015247 0 ustar 00root root 0000000 0000000 // Originally from Definitely Typed, see:
// https://github.com/DefinitelyTyped/DefinitelyTyped/blob/b4683d7/types/loglevel/index.d.ts
// Original definitions by: Stefan Profanter
// Gabor Szmetanko
// Christian Rackerseder
declare const log: log.RootLogger;
export = log;
declare namespace log {
/**
* Log levels
*/
interface LogLevel {
TRACE: 0;
DEBUG: 1;
INFO: 2;
WARN: 3;
ERROR: 4;
SILENT: 5;
}
/**
* Possible log level numbers.
*/
type LogLevelNumbers = LogLevel[keyof LogLevel];
/**
* Possible log level descriptors, may be string, lower or upper case, or number.
*/
type LogLevelDesc = LogLevelNumbers
| 'trace'
| 'debug'
| 'info'
| 'warn'
| 'error'
| 'silent'
| keyof LogLevel;
type LoggingMethod = (...message: any[]) => void;
type MethodFactory = (methodName: string, level: LogLevelNumbers, loggerName: string | symbol) => LoggingMethod;
interface RootLogger extends Logger {
/**
* 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.
*/
noConflict(): any;
/**
* This gets you a new logger object that works exactly like the root log object, but can have its level and
* logging methods set independently. All loggers must have a name (which is a non-empty string or a symbol)
* Calling * getLogger() multiple times with the same name will return an identical logger object.
* In large applications, it can be incredibly useful to turn logging on and off for particular modules as you are
* working with them. Using the getLogger() method lets you create a separate logger for each part of your
* application with its own logging level. Likewise, for small, independent modules, using a named logger instead
* of the default root logger allows developers using your module to selectively turn on deep, trace-level logging
* when trying to debug problems, while logging only errors or silencing logging altogether under normal
* circumstances.
* @param name The name of the produced logger
*/
getLogger(name: string | symbol): Logger;
/**
* This will return you the dictionary of all loggers created with getLogger, keyed off of their names.
*/
getLoggers(): { [name: string]: Logger };
/**
* A .default property for ES6 default import compatibility
*/
default: RootLogger;
}
interface Logger {
/**
* Available log levels.
*/
readonly levels: LogLevel;
/**
* Plugin API entry point. This will be called for each enabled method each time the level is set
* (including initially), and should return a MethodFactory to be used for the given log method, at the given level,
* for a logger with the given name. 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
*/
methodFactory: MethodFactory;
/**
* Output trace message to console.
* This will also include a full stack trace
*
* @param msg any data to log to the console
*/
trace(...msg: any[]): void;
/**
* Output debug message to console including appropriate icons
*
* @param msg any data to log to the console
*/
debug(...msg: any[]): void;
/**
* Output debug message to console including appropriate icons
*
* @param msg any data to log to the console
*/
log(...msg: any[]): void;
/**
* Output info message to console including appropriate icons
*
* @param msg any data to log to the console
*/
info(...msg: any[]): void;
/**
* Output warn message to console including appropriate icons
*
* @param msg any data to log to the console
*/
warn(...msg: any[]): void;
/**
* Output error message to console including appropriate icons
*
* @param msg any data to log to the console
*/
error(...msg: any[]): void;
/**
* 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.
*
* @param level as a string, like 'error' (case-insensitive) or as a number from 0 to 5 (or as log.levels. values)
* @param persist 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), or if you pass
* false as the optional 'persist' second argument, persistence will be skipped.
*/
setLevel(level: LogLevelDesc, persist?: boolean): void;
/**
* Returns the current logging level, as a value from LogLevel.
* It's very unlikely you'll need to use this for normal application logging; it's provided partly to help plugin
* development, and partly to let you optimize logging code as below, where debug data is only generated if the
* level is set such that it'll actually be logged. This probably doesn't affect you, unless you've run profiling
* on your code and you have hard numbers telling you that your log data generation is a real performance problem.
*/
getLevel(): LogLevel[keyof LogLevel];
/**
* This sets the current log level only if one has not been persisted and can’t be loaded. This is useful when
* initializing scripts; if a developer or user has previously called setLevel(), this won’t alter their settings.
* For example, your application might set the log level to error in a production environment, but when debugging
* an issue, you might call setLevel("trace") on the console to see all the logs. If that error setting was set
* using setDefaultLevel(), it will still say as trace on subsequent page loads and refreshes instead of resetting
* to error.
*
* The level argument takes is the same values that you might pass to setLevel(). Levels set using
* setDefaultLevel() never persist to subsequent page loads.
*
* @param level as a string, like 'error' (case-insensitive) or as a number from 0 to 5 (or as log.levels. values)
*/
setDefaultLevel(level: LogLevelDesc): void;
/**
* This enables all log messages, and is equivalent to log.setLevel("trace").
*
* @param persist 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), or if you pass
* false as the optional 'persist' second argument, persistence will be skipped.
*/
enableAll(persist?: boolean): void;
/**
* This disables all log messages, and is equivalent to log.setLevel("silent").
*
* @param persist 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), or if you pass
* false as the optional 'persist' second argument, persistence will be skipped.
*/
disableAll(persist?: boolean): void;
}
}
loglevel-1.7.1/lib/ 0000775 0000000 0000000 00000000000 13757442753 0014120 5 ustar 00root root 0000000 0000000 loglevel-1.7.1/lib/.jshintrc 0000664 0000000 0000000 00000000521 13757442753 0015743 0 ustar 00root root 0000000 0000000 {
"curly": false,
"eqeqeq": true,
"immed": true,
"latedef": true,
"newcap": true,
"noarg": true,
"sub": true,
"undef": true,
"boss": true,
"eqnull": true,
"es3": true,
"notypeof": true,
"globals": {
"console": false,
"exports": false,
"define": false,
"module": false,
"window": false
}
}
loglevel-1.7.1/lib/loglevel.js 0000664 0000000 0000000 00000021231 13757442753 0016266 0 ustar 00root root 0000000 0000000 /*
* loglevel - https://github.com/pimterry/loglevel
*
* Copyright (c) 2013 Tim Perry
* Licensed under the MIT license.
*/
(function (root, definition) {
"use strict";
if (typeof define === 'function' && define.amd) {
define(definition);
} else if (typeof module === 'object' && module.exports) {
module.exports = definition();
} else {
root.log = definition();
}
}(this, function () {
"use strict";
// Slightly dubious tricks to cut down minimized file size
var noop = function() {};
var undefinedType = "undefined";
var isIE = (typeof window !== undefinedType) && (typeof window.navigator !== undefinedType) && (
/Trident\/|MSIE /.test(window.navigator.userAgent)
);
var logMethods = [
"trace",
"debug",
"info",
"warn",
"error"
];
// Cross-browser bind equivalent that works at least back to IE6
function bindMethod(obj, methodName) {
var method = obj[methodName];
if (typeof method.bind === 'function') {
return method.bind(obj);
} else {
try {
return Function.prototype.bind.call(method, obj);
} catch (e) {
// Missing bind shim or IE8 + Modernizr, fallback to wrapping
return function() {
return Function.prototype.apply.apply(method, [obj, arguments]);
};
}
}
}
// Trace() doesn't print the message in IE, so for that case we need to wrap it
function traceForIE() {
if (console.log) {
if (console.log.apply) {
console.log.apply(console, arguments);
} else {
// In old IE, native console methods themselves don't have apply().
Function.prototype.apply.apply(console.log, [console, arguments]);
}
}
if (console.trace) console.trace();
}
// Build the best logging method possible for this env
// Wherever possible we want to bind, not wrap, to preserve stack traces
function realMethod(methodName) {
if (methodName === 'debug') {
methodName = 'log';
}
if (typeof console === undefinedType) {
return false; // No method possible, for now - fixed later by enableLoggingWhenConsoleArrives
} else if (methodName === 'trace' && isIE) {
return traceForIE;
} else if (console[methodName] !== undefined) {
return bindMethod(console, methodName);
} else if (console.log !== undefined) {
return bindMethod(console, 'log');
} else {
return noop;
}
}
// These private functions always need `this` to be set properly
function replaceLoggingMethods(level, loggerName) {
/*jshint validthis:true */
for (var i = 0; i < logMethods.length; i++) {
var methodName = logMethods[i];
this[methodName] = (i < level) ?
noop :
this.methodFactory(methodName, level, loggerName);
}
// Define log.log as an alias for log.debug
this.log = this.debug;
}
// In old IE versions, the console isn't present until you first open it.
// We build realMethod() replacements here that regenerate logging methods
function enableLoggingWhenConsoleArrives(methodName, level, loggerName) {
return function () {
if (typeof console !== undefinedType) {
replaceLoggingMethods.call(this, level, loggerName);
this[methodName].apply(this, arguments);
}
};
}
// By default, we use closely bound real methods wherever possible, and
// otherwise we wait for a console to appear, and then try again.
function defaultMethodFactory(methodName, level, loggerName) {
/*jshint validthis:true */
return realMethod(methodName) ||
enableLoggingWhenConsoleArrives.apply(this, arguments);
}
function Logger(name, defaultLevel, factory) {
var self = this;
var currentLevel;
var storageKey = "loglevel";
if (typeof name === "string") {
storageKey += ":" + name;
} else if (typeof name === "symbol") {
storageKey = undefined;
}
function persistLevelIfPossible(levelNum) {
var levelName = (logMethods[levelNum] || 'silent').toUpperCase();
if (typeof window === undefinedType || !storageKey) return;
// Use localStorage if available
try {
window.localStorage[storageKey] = levelName;
return;
} catch (ignore) {}
// Use session cookie as fallback
try {
window.document.cookie =
encodeURIComponent(storageKey) + "=" + levelName + ";";
} catch (ignore) {}
}
function getPersistedLevel() {
var storedLevel;
if (typeof window === undefinedType || !storageKey) return;
try {
storedLevel = window.localStorage[storageKey];
} catch (ignore) {}
// Fallback to cookies if local storage gives us nothing
if (typeof storedLevel === undefinedType) {
try {
var cookie = window.document.cookie;
var location = cookie.indexOf(
encodeURIComponent(storageKey) + "=");
if (location !== -1) {
storedLevel = /^([^;]+)/.exec(cookie.slice(location))[1];
}
} catch (ignore) {}
}
// If the stored level is not valid, treat it as if nothing was stored.
if (self.levels[storedLevel] === undefined) {
storedLevel = undefined;
}
return storedLevel;
}
/*
*
* Public logger API - see https://github.com/pimterry/loglevel for details
*
*/
self.name = name;
self.levels = { "TRACE": 0, "DEBUG": 1, "INFO": 2, "WARN": 3,
"ERROR": 4, "SILENT": 5};
self.methodFactory = factory || defaultMethodFactory;
self.getLevel = function () {
return currentLevel;
};
self.setLevel = function (level, persist) {
if (typeof level === "string" && self.levels[level.toUpperCase()] !== undefined) {
level = self.levels[level.toUpperCase()];
}
if (typeof level === "number" && level >= 0 && level <= self.levels.SILENT) {
currentLevel = level;
if (persist !== false) { // defaults to true
persistLevelIfPossible(level);
}
replaceLoggingMethods.call(self, level, name);
if (typeof console === undefinedType && level < self.levels.SILENT) {
return "No console available for logging";
}
} else {
throw "log.setLevel() called with invalid level: " + level;
}
};
self.setDefaultLevel = function (level) {
if (!getPersistedLevel()) {
self.setLevel(level, false);
}
};
self.enableAll = function(persist) {
self.setLevel(self.levels.TRACE, persist);
};
self.disableAll = function(persist) {
self.setLevel(self.levels.SILENT, persist);
};
// Initialize with the right level
var initialLevel = getPersistedLevel();
if (initialLevel == null) {
initialLevel = defaultLevel == null ? "WARN" : defaultLevel;
}
self.setLevel(initialLevel, false);
}
/*
*
* Top-level API
*
*/
var defaultLogger = new Logger();
var _loggersByName = {};
defaultLogger.getLogger = function getLogger(name) {
if ((typeof name !== "symbol" && typeof name !== "string") || name === "") {
throw new TypeError("You must supply a name when creating a logger.");
}
var logger = _loggersByName[name];
if (!logger) {
logger = _loggersByName[name] = new Logger(
name, defaultLogger.getLevel(), defaultLogger.methodFactory);
}
return logger;
};
// Grab the current global log variable in case of overwrite
var _log = (typeof window !== undefinedType) ? window.log : undefined;
defaultLogger.noConflict = function() {
if (typeof window !== undefinedType &&
window.log === defaultLogger) {
window.log = _log;
}
return defaultLogger;
};
defaultLogger.getLoggers = function getLoggers() {
return _loggersByName;
};
// ES6 default export, for compatibility
defaultLogger['default'] = defaultLogger;
return defaultLogger;
}));
loglevel-1.7.1/package.json 0000664 0000000 0000000 00000003334 13757442753 0015643 0 ustar 00root root 0000000 0000000 {
"name": "loglevel",
"description": "Minimal lightweight logging for JavaScript, adding reliable log level methods to any available console.log methods",
"version": "1.7.1",
"homepage": "https://github.com/pimterry/loglevel",
"author": {
"name": "Tim Perry",
"email": "pimterry@gmail.com",
"url": "http://tim-perry.co.uk"
},
"repository": {
"type": "git",
"url": "git://github.com/pimterry/loglevel.git"
},
"bugs": {
"url": "https://github.com/pimterry/loglevel/issues"
},
"funding": {
"type": "tidelift",
"url": "https://tidelift.com/funding/github/npm/loglevel"
},
"license": "MIT",
"main": "lib/loglevel.js",
"types": "./index.d.ts",
"engines": {
"node": ">= 0.6.0"
},
"scripts": {
"test": "grunt test && tsc --noEmit ./test/type-test.ts",
"ci": "grunt ci",
"dist": "grunt dist",
"watch": "grunt watch"
},
"dependencies": {},
"devDependencies": {
"@types/core-js": "2.5.0",
"@types/node": "^12.0.4",
"grunt": "~0.4.5",
"grunt-cli": "~0.1.13",
"grunt-contrib-clean": "^0.6.0",
"grunt-contrib-concat": "~0.5.0",
"grunt-contrib-connect": "~0.8.0",
"grunt-contrib-jasmine": "~0.5.2",
"grunt-contrib-jshint": "^1.1.0",
"grunt-contrib-qunit": "~0.5.2",
"grunt-contrib-uglify": "~0.5.1",
"grunt-contrib-watch": "~0.6.1",
"grunt-coveralls": "^1.0.0",
"grunt-jasmine-node": "~0.2.1",
"grunt-open": "~0.2.3",
"grunt-preprocess": "^4.0.0",
"grunt-saucelabs": "^8.2.0",
"grunt-template-jasmine-istanbul": "~0.2.5",
"grunt-template-jasmine-requirejs": "~0.1.6",
"qunitjs": "1.14.0",
"typescript": "^3.5.1"
},
"keywords": [
"log",
"logger",
"logging",
"browser"
]
}
loglevel-1.7.1/test/ 0000775 0000000 0000000 00000000000 13757442753 0014331 5 ustar 00root root 0000000 0000000 loglevel-1.7.1/test/.jshintrc 0000664 0000000 0000000 00000001152 13757442753 0016155 0 ustar 00root root 0000000 0000000 {
"curly": true,
"globalstrict": true,
"eqeqeq": true,
"immed": true,
"latedef": true,
"newcap": true,
"noarg": true,
"sub": true,
"undef": true,
"boss": true,
"eqnull": true,
"es3": true,
"globals": {
"window": true,
"console": true,
"define": false,
"require": false,
"exports": false,
"_": false,
"afterEach": false,
"beforeEach": false,
"confirm": false,
"context": false,
"describe": false,
"xdescribe": false,
"expect": false,
"it": false,
"jasmine": false,
"waitsFor": false,
"runs": false,
"Symbol": false
}
}
loglevel-1.7.1/test/console-fallback-test.js 0000664 0000000 0000000 00000006275 13757442753 0021055 0 ustar 00root root 0000000 0000000 "use strict";
function consoleLogIsCalledBy(log, methodName) {
it(methodName + " calls console.log", function() {
log.setLevel(log.levels.TRACE);
log[methodName]("Log message for call to " + methodName);
expect(console.log.calls.length).toEqual(1);
});
}
function mockConsole() {
return {"log" : jasmine.createSpy("console.log")};
}
define(['../lib/loglevel'], function(log) {
var originalConsole = window.console;
describe("Fallback functionality:", function() {
describe("with no console present", function() {
beforeEach(function() {
window.console = undefined;
});
afterEach(function() {
window.console = originalConsole;
});
it("silent method calls are allowed", function() {
var result = log.setLevel(log.levels.SILENT);
log.trace("hello");
expect(result).toBeUndefined();
});
it("setting an active level gently returns an error string", function() {
var result = log.setLevel(log.levels.TRACE);
expect(result).toEqual("No console available for logging");
});
it("active method calls are allowed, once the active setLevel fails", function() {
log.setLevel(log.levels.TRACE);
log.trace("hello");
});
describe("if a console later appears", function () {
it("logging is re-enabled and works correctly when next used", function () {
log.setLevel(log.levels.WARN);
window.console = mockConsole();
log.error("error");
expect(window.console.log).toHaveBeenCalled();
});
it("logging is re-enabled but does nothing when used at a blocked level", function () {
log.setLevel(log.levels.WARN);
window.console = mockConsole();
log.trace("trace");
expect(window.console.log).not.toHaveBeenCalled();
});
it("changing level works correctly from that point", function () {
window.console = mockConsole();
var result = log.setLevel(log.levels.WARN);
expect(result).toBeUndefined();
});
});
});
describe("with a console that only supports console.log", function() {
beforeEach(function() {
window.console = mockConsole();
});
afterEach(function() {
window.console = originalConsole;
});
it("log can be set to silent", function() {
log.setLevel(log.levels.SILENT);
});
it("log can be set to an active level", function() {
log.setLevel(log.levels.ERROR);
});
consoleLogIsCalledBy(log, "trace");
consoleLogIsCalledBy(log, "debug");
consoleLogIsCalledBy(log, "info");
consoleLogIsCalledBy(log, "warn");
consoleLogIsCalledBy(log, "trace");
});
});
});
loglevel-1.7.1/test/cookie-test.js 0000664 0000000 0000000 00000010071 13757442753 0017114 0 ustar 00root root 0000000 0000000 "use strict";
define(['test/test-helpers'], function(testHelpers) {
var describeIf = testHelpers.describeIf;
var it = testHelpers.itWithFreshLog;
var originalConsole = window.console;
var originalDocument = window.document;
describeIf(testHelpers.isCookieStorageAvailable() && !testHelpers.isLocalStorageAvailable(),
"Cookie-only persistence tests:", function() {
beforeEach(function() {
window.console = {"log" : jasmine.createSpy("console.log")};
this.addMatchers({
"toBeAtLevel" : testHelpers.toBeAtLevel,
"toBeTheStoredLevel" : testHelpers.toBeTheLevelStoredByCookie
});
});
afterEach(function() {
window.console = originalConsole;
});
describe("If no level is saved", function() {
beforeEach(function() {
testHelpers.clearStoredLevels();
});
it("log level is set to warn by default", function(log) {
expect(log).toBeAtLevel("warn");
});
it("warn is persisted as the current level", function(log) {
expect("warn").toBeTheStoredLevel();
});
it("log can be set to info level", function(log) {
log.setLevel("info");
expect(log).toBeAtLevel("info");
});
it("log.setLevel() sets a cookie with the given level", function(log) {
log.setLevel("debug");
expect("debug").toBeTheStoredLevel();
});
});
describe("If info level is saved", function() {
beforeEach(function() {
testHelpers.setStoredLevel("info");
});
it("info is the default log level", function(log) {
expect(log).toBeAtLevel("info");
});
it("log can be changed to warn level", function(log) {
log.setLevel("warn");
expect(log).toBeAtLevel("warn");
});
it("log.setLevel() overwrites the saved level", function(log) {
log.setLevel("error");
expect("error").toBeTheStoredLevel();
expect("info").not.toBeTheStoredLevel();
});
});
describe("If the level is saved with other data", function() {
beforeEach(function() {
window.document.cookie = "qwe=asd";
window.document.cookie = "loglevel=ERROR";
window.document.cookie = "msg=hello world";
});
it("error is the default log level", function(log) {
expect(log).toBeAtLevel("error");
});
it("log can be changed to silent level", function(log) {
log.setLevel("silent");
expect(log).toBeAtLevel("silent");
});
it("log.setLevel() overrides the saved level only", function(log) {
log.setLevel("debug");
expect('debug').toBeTheStoredLevel();
expect(window.document.cookie).toContain("msg=hello world");
});
});
describe("If the level cookie is set incorrectly", function() {
beforeEach(function() {
testHelpers.setCookieStoredLevel('gibberish');
});
it("warn is the default log level", function(log) {
expect(log).toBeAtLevel("warn");
});
it("warn is persisted as the current level, overriding the invalid cookie", function(log) {
expect("warn").toBeTheStoredLevel();
});
it("log can be changed to info level", function(log) {
log.setLevel("info");
expect(log).toBeAtLevel("info");
});
it("log.setLevel() overrides the saved level with the new level", function(log) {
expect('debug').not.toBeTheStoredLevel();
log.setLevel("debug");
expect('debug').toBeTheStoredLevel();
});
});
});
});
loglevel-1.7.1/test/default-level-test.js 0000664 0000000 0000000 00000003603 13757442753 0020377 0 ustar 00root root 0000000 0000000 "use strict";
define(['test/test-helpers'], function(testHelpers) {
var describeIf = testHelpers.describeIf;
var it = testHelpers.itWithFreshLog;
var originalConsole = window.console;
describe("Setting default log level tests:", function() {
beforeEach(function() {
window.console = {"log" : jasmine.createSpy("console.log")};
this.addMatchers({
"toBeAtLevel" : testHelpers.toBeAtLevel,
"toBeTheStoredLevel" : testHelpers.toBeTheLevelStoredByLocalStorage
});
testHelpers.clearStoredLevels();
});
afterEach(function() {
window.console = originalConsole;
});
describe("If no level is saved", function() {
it("new level is always set", function(log) {
log.setDefaultLevel("trace");
expect(log).toBeAtLevel("trace");
});
it("level is not persisted", function(log) {
log.setDefaultLevel("debug");
expect("debug").not.toBeTheStoredLevel();
});
});
describe("If a level is saved", function () {
beforeEach(function () {
testHelpers.setStoredLevel("trace");
});
it("saved level is not modified", function (log) {
log.setDefaultLevel("debug");
expect(log).toBeAtLevel("trace");
});
});
describe("If the level is stored incorrectly", function() {
beforeEach(function() {
testHelpers.setLocalStorageStoredLevel("gibberish");
});
it("new level is set", function(log) {
log.setDefaultLevel("debug");
expect(log).toBeAtLevel("debug");
expect("debug").not.toBeTheStoredLevel();
});
});
});
});
loglevel-1.7.1/test/get-current-level-test.js 0000664 0000000 0000000 00000002761 13757442753 0021216 0 ustar 00root root 0000000 0000000 "use strict";
define(['test/test-helpers'], function(testHelpers) {
var describeIf = testHelpers.describeIf;
var it = testHelpers.itWithFreshLog;
var originalConsole = window.console;
describe("Setting default log level tests:", function() {
beforeEach(function() {
window.console = {"log" : jasmine.createSpy("console.log")};
});
afterEach(function() {
window.console = originalConsole;
});
describe("If no level is saved", function() {
it("current level is the default level", function(log) {
log.setDefaultLevel("trace");
expect(log.getLevel()).toBe(log.levels.TRACE);
});
});
describe("If a level is saved", function () {
beforeEach(function () {
testHelpers.setStoredLevel("trace");
});
it("current level is the level which has been saved", function (log) {
log.setDefaultLevel("debug");
expect(log.getLevel()).toBe(log.levels.TRACE);
});
});
describe("If the level is stored incorrectly", function() {
beforeEach(function() {
testHelpers.setLocalStorageStoredLevel("gibberish");
});
it("current level is the default level", function(log) {
log.setDefaultLevel("debug");
expect(log.getLevel()).toBe(log.levels.DEBUG);
});
});
});
});
loglevel-1.7.1/test/global-integration-with-new-context.js 0000664 0000000 0000000 00000001770 13757442753 0023677 0 ustar 00root root 0000000 0000000 /* global MyCustomLogger, log */
"use strict";
describe("loglevel from a global