"
8 | ],
9 | "description": "Safe, production happy, colourful logging for chrome & firefox",
10 | "moduleType": [
11 | "amd",
12 | "global",
13 | "node",
14 | "umd"
15 | ],
16 | "keywords": [
17 | "log",
18 | "console",
19 | "logging"
20 | ],
21 | "license": "MIT",
22 | "ignore": [
23 | "**/.*",
24 | "node_modules",
25 | "bower_components",
26 | "test",
27 | "tests"
28 | ]
29 | }
30 |
--------------------------------------------------------------------------------
/test/no-local-storage.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
10 |
11 |
12 |
13 |
29 |
--------------------------------------------------------------------------------
/test/enabled.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
8 |
9 |
10 |
33 |
--------------------------------------------------------------------------------
/test/alternative-key.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
8 |
9 |
10 |
11 |
32 |
--------------------------------------------------------------------------------
/test/regex.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
8 |
9 |
10 |
34 |
--------------------------------------------------------------------------------
/test/not-regex.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
8 |
9 |
10 |
34 |
--------------------------------------------------------------------------------
/test/no-separator.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
8 |
9 |
10 |
37 |
--------------------------------------------------------------------------------
/test/separator.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
8 |
9 |
10 |
37 |
--------------------------------------------------------------------------------
/test/helpers/function.bind.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Polyfill for phantomjs's lack of .bind()
3 | */
4 | if (!Function.prototype.bind) {
5 | Function.prototype.bind = function(oThis) {
6 | if (typeof this !== 'function') {
7 | // closest thing possible to the ECMAScript 5 internal IsCallable function
8 | throw new TypeError(
9 | 'Function.prototype.bind - what is trying to be bound is not callable'
10 | );
11 | }
12 |
13 | var aArgs = Array.prototype.slice.call(arguments, 1),
14 | fToBind = this,
15 | fNOP = function() {},
16 | fBound = function() {
17 | return fToBind.apply(
18 | oThis,
19 | aArgs.concat(Array.prototype.slice.call(arguments))
20 | );
21 | };
22 |
23 | fNOP.prototype = this.prototype;
24 | fBound.prototype = new fNOP();
25 |
26 | return fBound;
27 | };
28 | }
29 |
--------------------------------------------------------------------------------
/test/args.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
6 |
7 |
8 |
9 |
34 |
--------------------------------------------------------------------------------
/.github/workflows/browser-tests.yml:
--------------------------------------------------------------------------------
1 | name: Browser Tests
2 |
3 | on: [push]
4 |
5 | jobs:
6 | build:
7 |
8 | runs-on: ubuntu-latest
9 |
10 | strategy:
11 | matrix:
12 | node-version: [10.x]
13 |
14 | steps:
15 | - uses: actions/checkout@v1
16 |
17 | - name: Use Node.js ${{ matrix.node-version }}
18 | uses: actions/setup-node@v1
19 | with:
20 | node-version: ${{ matrix.node-version }}
21 |
22 | - name: Cache node modules
23 | uses: actions/cache@v1
24 | with:
25 | path: node_modules
26 | key: ${{ runner.OS }}-build-${{ hashFiles('**/package-lock.json') }}
27 | restore-keys: |
28 | ${{ runner.OS }}-build-${{ env.cache-name }}-
29 | ${{ runner.OS }}-build-
30 | ${{ runner.OS }}-
31 |
32 | - name: Install dependencies
33 | run: npm install
34 |
35 | - name: Build + test
36 | run: npm test
37 |
--------------------------------------------------------------------------------
/test/no-padding.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
8 |
9 |
10 |
37 |
--------------------------------------------------------------------------------
/test/padLength.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
8 |
9 |
10 |
37 |
--------------------------------------------------------------------------------
/test/index.js:
--------------------------------------------------------------------------------
1 | var runTestPage = require('./helpers/runTestPage');
2 |
3 | var scripts = [
4 | 'test/enabled.html',
5 | 'test/disabled.html',
6 | 'test/no-local-storage.html',
7 | 'test/alternative-key.html',
8 | 'test/regex.html',
9 | 'test/not-regex.html',
10 | 'test/color-map.html',
11 | 'test/separator.html',
12 | 'test/no-separator.html',
13 | 'test/padLength.html',
14 | 'test/no-padding.html',
15 | 'test/args.html'
16 | ];
17 |
18 | async function runAllScripts() {
19 | const results = { passed: [], failed: [] };
20 |
21 | for (const script of scripts) {
22 | console.log(`\n--- Running ${script} ---`);
23 | const passed = await runTestPage(script);
24 | if (passed) {
25 | results.passed.push(script);
26 | } else {
27 | results.failed.push(script);
28 | }
29 | }
30 |
31 | if (results.failed.length === 0) {
32 | console.log('All test suites passed');
33 | } else {
34 | console.log(
35 | `${results.failed.length} of ${results.failed.length +
36 | results.passed.length} suites failed.`
37 | );
38 | }
39 |
40 | const exitCode = results.failed.length === 0 ? 0 : 1;
41 | process.exit(exitCode);
42 | }
43 |
44 | runAllScripts();
45 |
--------------------------------------------------------------------------------
/test/color-map.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
8 |
9 |
10 |
60 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "bows",
3 | "version": "1.7.2",
4 | "description": "Rainbowed console logs for chrome, opera and firefox in development.",
5 | "main": "bows.js",
6 | "scripts": {
7 | "build": "node build.js",
8 | "prettier": "prettier --single-quote --write {.,test}/**/*.js *.js test/**/*.html",
9 | "prettier-check": "prettier --single-quote --check {.,test}/**/*.js *.js test/**/*.html",
10 | "test": "node build.js && npm run prettier-check && node test/index.js",
11 | "preversion": "git checkout master && git pull && npm ls",
12 | "publish-patch": "npm run preversion && npm version patch && git push origin master --tags && npm publish",
13 | "publish-minor": "npm run preversion && npm version minor && git push origin master --tags && npm publish",
14 | "publish-major": "npm run preversion && npm version major && git push origin master --tags && npm publish"
15 | },
16 | "dependencies": {
17 | "andlog": "^1.0.2"
18 | },
19 | "devDependencies": {
20 | "browserify": "^5.10.0",
21 | "prettier": "1.19.0",
22 | "puppeteer": "^2.0.0",
23 | "uglify-js": "^2.3.6"
24 | },
25 | "author": "Philip Roberts",
26 | "license": "MIT",
27 | "readmeFilename": "README.md",
28 | "gitHead": "bd7b0c00f47771a342ddc098cdc7e5ee5b4a53b3",
29 | "directories": {
30 | "example": "example"
31 | },
32 | "repository": {
33 | "type": "git",
34 | "url": "git://github.com/latentflip/bows.git"
35 | },
36 | "keywords": [
37 | "color",
38 | "logging",
39 | "chrome",
40 | "console"
41 | ],
42 | "bugs": {
43 | "url": "https://github.com/latentflip/bows/issues"
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/example/example.html:
--------------------------------------------------------------------------------
1 |
9 |
10 |
11 |
12 |
13 |
54 |
55 |
56 |
57 |
58 |
Psst.
59 | View the source/Open the console.
60 |
61 |
--------------------------------------------------------------------------------
/test/helpers/runTestPage.js:
--------------------------------------------------------------------------------
1 | var puppeteer = require('puppeteer');
2 | var Path = require('path');
3 |
4 | module.exports = async function runTestPage(path) {
5 | var exit = 0;
6 |
7 | var actualLogs = [];
8 | var pageErrors = [];
9 |
10 | const browser = await puppeteer.launch();
11 | const page = await browser.newPage();
12 |
13 | page.on('console', msg => {
14 | actualLogs.push(msg.text());
15 | });
16 |
17 | page.on('pageerror', error => {
18 | console.log('Exception: ', error.message);
19 | pageErrors.push(error.message);
20 | });
21 |
22 | await page.goto(`file:${Path.join(__dirname, '..', '..', path)}`);
23 | var customTests = await page.evaluate(function() {
24 | return !!window.customTests;
25 | });
26 |
27 | if (customTests) {
28 | var customResults = await page.evaluate(function(l) {
29 | return window.customTests(l);
30 | }, actualLogs);
31 |
32 | customResults.forEach(function(result) {
33 | if (!result[0]) {
34 | console.log('✖ ', result[1]);
35 | exit = 1;
36 | } else {
37 | console.log('✔', result[1]);
38 | }
39 | });
40 |
41 | return exit === 0 && pageErrors.length === 0;
42 | }
43 |
44 | var expectedLogs = await page.evaluate(function() {
45 | return window.expectedLogs;
46 | });
47 |
48 | await browser.close();
49 |
50 | var exit = 0;
51 |
52 | expectedLogs.forEach(function(expectedLog, i) {
53 | if (expectedLog !== actualLogs[i]) {
54 | console.log('✖ Log mismatch');
55 | console.log(' Expected | "', expectedLog, '"');
56 | console.log(' Received | "', actualLogs[i], '"');
57 | exit = 1;
58 | } else {
59 | console.log('✔', expectedLog);
60 | }
61 | });
62 |
63 | if (expectedLogs.length === actualLogs.length) {
64 | console.log('✔ Received ', expectedLogs.length, 'logs');
65 | } else {
66 | console.log(
67 | '✖ Expected',
68 | expectedLogs.length,
69 | 'logs, received',
70 | actualLogs.length
71 | );
72 |
73 | console.log('Expected:');
74 | console.log(
75 | expectedLogs
76 | .map(function(s) {
77 | return '"' + s + '"';
78 | })
79 | .join(' ; ')
80 | );
81 |
82 | console.log('Actual:');
83 | console.log(
84 | actualLogs
85 | .map(function(s) {
86 | return '"' + s + '"';
87 | })
88 | .join(' ; ')
89 | );
90 |
91 | exit = 1;
92 | }
93 |
94 | return exit === 0 && pageErrors.length === 0;
95 | };
96 |
--------------------------------------------------------------------------------
/bows.js:
--------------------------------------------------------------------------------
1 | (function() {
2 | function checkColorSupport() {
3 | if (typeof window === 'undefined' || typeof navigator === 'undefined') {
4 | return false;
5 | }
6 |
7 | var chrome = !!window.chrome,
8 | firefox = /firefox/i.test(navigator.userAgent),
9 | firefoxVersion,
10 | electron = process && process.versions && process.versions.electron;
11 |
12 | if (firefox) {
13 | var match = navigator.userAgent.match(/Firefox\/(\d+\.\d+)/);
14 | if (match && match[1] && Number(match[1])) {
15 | firefoxVersion = Number(match[1]);
16 | }
17 | }
18 | return chrome || firefoxVersion >= 31.0 || electron;
19 | }
20 |
21 | function getLocalStorageSafely() {
22 | var localStorage;
23 | try {
24 | localStorage = window.localStorage;
25 | } catch (e) {
26 | // failed: access to localStorage is denied
27 | }
28 | return localStorage;
29 | }
30 |
31 | var yieldColor = function() {
32 | var goldenRatio = 0.618033988749895;
33 | hue += goldenRatio;
34 | hue = hue % 1;
35 | return hue * 360;
36 | };
37 |
38 | var inNode = typeof window === 'undefined',
39 | ls = !inNode && getLocalStorageSafely(),
40 | debugKey = ls && ls.andlogKey ? ls.andlogKey : 'debug',
41 | debug = ls && ls[debugKey] ? ls[debugKey] : false,
42 | logger = require('andlog'),
43 | bind = Function.prototype.bind,
44 | hue = 0,
45 | padding = true,
46 | separator = '|',
47 | padLength = 15,
48 | noop = function() {},
49 | // if ls.debugColors is set, use that, otherwise check for support
50 | colorsSupported =
51 | ls && ls.debugColors ? ls.debugColors !== 'false' : checkColorSupport(),
52 | bows = null,
53 | debugRegex = null,
54 | invertRegex = false,
55 | moduleColorsMap = {};
56 |
57 | if (debug && debug[0] === '!' && debug[1] === '/') {
58 | invertRegex = true;
59 | debug = debug.slice(1);
60 | }
61 | debugRegex =
62 | debug &&
63 | debug[0] === '/' &&
64 | new RegExp(debug.substring(1, debug.length - 1));
65 |
66 | var logLevels = ['log', 'debug', 'warn', 'error', 'info'];
67 |
68 | //Noop should noop
69 | for (var i = 0, ii = logLevels.length; i < ii; i++) {
70 | noop[logLevels[i]] = noop;
71 | }
72 |
73 | bows = function(str) {
74 | // If localStorage is not available just don't log
75 | if (!ls) return noop;
76 |
77 | var msg, colorString, logfn;
78 |
79 | if (padding) {
80 | msg = str.slice(0, padLength);
81 | msg += Array(padLength + 3 - msg.length).join(' ') + separator;
82 | } else {
83 | msg = str + Array(3).join(' ') + separator;
84 | }
85 |
86 | if (debugRegex) {
87 | var matches = str.match(debugRegex);
88 | if ((!invertRegex && !matches) || (invertRegex && matches)) return noop;
89 | }
90 |
91 | if (!bind) return noop;
92 |
93 | var logArgs = [logger];
94 | if (colorsSupported) {
95 | if (!moduleColorsMap[str]) {
96 | moduleColorsMap[str] = yieldColor();
97 | }
98 | var color = moduleColorsMap[str];
99 | msg = '%c' + msg;
100 | colorString = 'color: hsl(' + color + ',99%,40%); font-weight: bold';
101 |
102 | logArgs.push(msg, colorString);
103 | } else {
104 | logArgs.push(msg);
105 | }
106 |
107 | if (arguments.length > 1) {
108 | var args = Array.prototype.slice.call(arguments, 1);
109 | logArgs = logArgs.concat(args);
110 | }
111 |
112 | logfn = bind.apply(logger.log, logArgs);
113 |
114 | logLevels.forEach(function(f) {
115 | logfn[f] = bind.apply(logger[f] || logfn, logArgs);
116 | });
117 | return logfn;
118 | };
119 |
120 | bows.config = function(config) {
121 | if (config.padLength) {
122 | padLength = config.padLength;
123 | }
124 |
125 | if (typeof config.padding === 'boolean') {
126 | padding = config.padding;
127 | }
128 |
129 | if (config.separator) {
130 | separator = config.separator;
131 | } else if (config.separator === false || config.separator === '') {
132 | separator = '';
133 | }
134 | };
135 |
136 | if (typeof module !== 'undefined') {
137 | module.exports = bows;
138 | } else {
139 | window.bows = bows;
140 | }
141 | }.call());
142 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Bows
2 | 
3 | Safe, production happy, colourful logging - makes reading your logs _much_ easier.
4 |
5 |
6 | (Rain)bows makes logging debug messages in your apps much nicer.
7 | - It allows you to create custom loggers for each module in your app, that prefix all log messages with the name of the app, so that you can scan the messages more easily.
8 | - It colors the prefix differently and distinctly for each logger/module so that it's even easier to read.
9 | - It can be safely used in production, where logging will be disabled by default, so that you can leave log messages in your code.
10 | - Loggers safely wrap console.log, to maintain the line number from where they are called in the console output.
11 |
12 | 
13 |
14 | ## Installation
15 |
16 | If you are using browserify, you'll want something like:
17 |
18 | ```
19 | npm install bows --save
20 | ```
21 |
22 | If you use Bower:
23 |
24 | ```
25 | bower install bows --save
26 | ```
27 |
28 | Otherwise, download either [bows.js](https://raw.github.com/latentflip/bows/master/dist/bows.js) or [bows.min.js](https://raw.github.com/latentflip/bows/master/dist/bows.min.js).
29 |
30 | ## Features
31 |
32 | * Easily create prefixes for your logs, so that you can distinguish between logs from different parts of your app easily.
33 | * If supported, prefixes will be color coded for even easier identification.
34 | * Can be safely used in production, as logs will be disabled for your users, but can be enabled by you with a local storage flag.
35 | * Greppable logs by setting `localStorage.debug = /Foo/` to only display logs for modules matching the regex to help you focus in development.
36 | * Invert regex to remove logs matching with: `localStorage.debug ='!/Foo/`
37 | * Customize the localStorage key by setting `localStorage.andlogKey` and you can use `localStorage.` to set your log grepping.
38 |
39 | # Browser Support
40 |
41 | * Works in all reasonable browsers
42 | * Supports colors in chrome, opera, firefox >= 31.0, electron
43 |
44 | ## Usage
45 | - Works great in browserify and the browser.
46 | - Creating a new logger:
47 | - Browserify: `var log = require('bows')("My Module Name")`
48 | - Browser: `var log = bows("My Module Name")`
49 | - Then using it is easy:
50 | - `log("Module loaded") //-> "My Module Name | Module Loaded"`
51 | - `log("Did something") //-> "My Module Name | Did something"`
52 | - Typically each seperate module/view/etc in your app would create it's own logger. It will be assigned it's own color to make it easy to spot logs from different modules.
53 | - You can pass additional arguments to `bows` which will be automatically prepended to each message, e.g.:
54 |
55 | ```js
56 | var log = bows("My App", "[ChuckNorris]");
57 | log("Kicks ass!");
58 | //outputs:
59 | //My App | [ChuckNorris] Kicks ass!
60 | ```
61 |
62 | - Logging is disabled by default. To enable logging, set `localStorage.debug = true` in your console and refresh the page.
63 | - To **disable** logging again, you must do `delete localStorage.debug` (`localStorage.debug = false` will not work).
64 | - You can leave the code in in production, and log() will just safely no-op unless localStorage.debug is set.
65 | - Where colors are not supported, bows will just log plain text, but still with the module prefix.
66 | - If you wish to manually disable colors in an environment because detection is incorrect, set `localStorage.debugColors = false`, to reenable `delete localStorage.debugColors`.
67 |
68 | ## Example
69 |
70 | ```javascript
71 | //Should be set in your console to see messages
72 | localStorage.debug = true
73 | //Configure the max length of module names (optional)
74 | bows.config({ padLength: 10 })
75 |
76 | var logger1 = bows('Module 1')
77 | var logger2 = bows('Module 2')
78 | var logger3 = bows('Module 3')
79 |
80 | logger1("We started up")
81 | logger2("We did something too")
82 | logger3("I'm here")
83 | logger3("I'm still here")
84 | logger2("I'm tired")
85 | logger1("We're done here")
86 | ```
87 |
88 | Result:
89 |
90 | 
91 |
92 | ## Test
93 |
94 | __Status:__ [](https://travis-ci.org/latentflip/bows)
95 |
96 | This project uses `phantomjs` for tests. To run the tests install the development dependencies and then run:
97 |
98 | ```bash
99 | npm test
100 | ```
101 |
102 | ### New tests
103 |
104 | Add a file in `test`, refer to enabled.html/disabled.html, then add the script to the array in test/index.js.
105 |
106 | ## License & Credits
107 |
108 | MIT
109 |
110 | Copyright [@philip\_roberts](http://twitter.com/philip\_roberts) / [latentflip.com](http://latentflip.com).
111 |
112 | With contributions from:
113 | * [@lloydwatkin](https://twitter.com/lloydwatkin).
114 | * [@camillereynders](https://twitter.com/camillereynders).
115 |
116 | Bows depends on [andlog](http://github.com/henrikjoreteg/andlog), a nice little logging module by [@HenrikJoreteg](https://twitter.com/henrikjoreteg).
117 |
118 |
119 | ## Contributing
120 |
121 | Please feel free to raise issues, or make contributions:
122 |
123 | ```bash
124 | git clone https://github.com/latentflip/bows.git
125 | cd bows
126 | npm install #install dependencies
127 | #edit bows.js
128 | npm test
129 | npm run build.js #build dist/bows.js and dist/bows.min.js, also done by `npm test`
130 | ```
131 |
132 |
--------------------------------------------------------------------------------