Skip to content

Commit 48103b4

Browse files
committed
doc, include ms
1 parent 49e801e commit 48103b4

File tree

7 files changed

+261
-127
lines changed

7 files changed

+261
-127
lines changed

.github/workflows/nodejs.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,10 @@ jobs:
1010

1111
strategy:
1212
matrix:
13-
node-version: [18.x]
13+
node-version: [22.x]
1414

1515
steps:
16-
- uses: actions/checkout@v4
16+
- uses: actions/checkout@v5
1717
- name: Use Node.js ${{ matrix.node-version }}
1818
uses: actions/setup-node@v4
1919
with:

README.md

Lines changed: 64 additions & 102 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# debug
2-
![tests](https://github.com/substrate-system/debug/actions/workflows/nodejs.yml/badge.svg)
2+
[![tests](https://img.shields.io/github/actions/workflow/status/substrate-system/debug/nodejs.yml?style=flat-square)](https://github.com/substrate-system/debug/actions/workflows/nodejs.yml)
33
[![module](https://img.shields.io/badge/module-ESM-blue?style=flat-square)](README.md)
44
[![types](https://img.shields.io/npm/types/@substrate-system/debug?style=flat-square)](README.md)
55
[![semantic versioning](https://img.shields.io/badge/semver-2.0.0-blue?logo=semver&style=flat-square)](https://semver.org/)
@@ -8,15 +8,15 @@
88

99

1010
A tiny JavaScript debugging utility that works in Node.js and browsers.
11-
Use environment variables to control logging, so there are no ridiculous
12-
console log statements in production.
11+
Use environment variables to control logging in Node.js, and localStorage
12+
to control logging in browsers, so there are no ridiculous console log
13+
statements in production.
1314

1415
This is based on [debug](https://github.com/debug-js/debug).
1516
It's been rewritten to use contemporary JS.
1617

17-
In the browser, this should work well with [vite](https://vite.dev/). As is
18-
convention, this will look for an env variable prefixed with `VITE_`. So pass
19-
env variables like `VITE_DEBUG="foo"`.
18+
In the browser, this uses localStorage to control debug output.
19+
In Node.js, it uses the environmen variable `DEBUG`.
2020

2121
**Featuring:**
2222
* Use [exports](https://github.com/substrate-system/debug/blob/main/package.json#L31)
@@ -30,154 +30,116 @@ generated by typescript.
3030

3131
<!-- toc -->
3232

33+
- [Install](#install)
3334
- [Browser](#browser)
34-
- [config](#config)
35-
* [namespace](#namespace)
36-
* [NODE_ENV + Vite](#node_env--vite)
37-
- [install](#install)
3835
- [Node JS](#node-js)
39-
* [NODE_ENV](#node_env)
40-
- [develop](#develop)
36+
- [Config](#config)
37+
* [Namespace](#namespace)
38+
* [Enable all namespaces](#enable-all-namespaces)
39+
* [Enable specific namespaces](#enable-specific-namespaces)
40+
* [Force logging with boolean true](#force-logging-with-boolean-true)
41+
- [Develop](#develop)
4142
* [browser](#browser)
42-
- [test](#test)
43-
* [node](#node)
43+
- [Test](#test)
44+
* [Node](#node)
4445

4546
<!-- tocstop -->
4647

47-
## Browser
48-
49-
In the browser, this will look for `VITE_DEBUG` import.meta variable,
50-
and `DEBUG` in `localStorage`.
51-
52-
```js
53-
import Debug from '@substrate-system/debug'
54-
55-
localStorage.setItem('DEBUG', 'browser:123')
48+
## Install
5649

57-
const debug = Debug('browser:*')
58-
59-
debug('hello logs')
60-
// will log, b/c DEBUG in localStorage is browser:123
50+
```sh
51+
npm i -D @substrate-system/debug
6152
```
6253

54+
**Browser usage**: Use `localStorage` `DEBUG` key.
55+
**Node.js usage**: Use environment variable `DEBUG`.
6356

64-
## config
65-
66-
### namespace
67-
Works with `vite` or other systems. This will look at `import.meta.env`, or
68-
an arbitrary object you can pass in, or `localStorage` in the browser.
69-
70-
```js
71-
import Debug from '@substrate-system/debug'
72-
73-
// look at `import.meta.env.VITE_DEBUG`
74-
const debug = Debug('example')
75-
76-
// or call with your own env object
77-
const debug = Debug('example', { DEBUG: 'example' })
78-
```
57+
## Browser
7958

80-
If you create an instance without passing in a `namespace` string, then this
81-
will log iff anything other than `false` is passed as an argument.
59+
In the browser, this looks for the `DEBUG` key in `localStorage`.
8260

8361
```js
8462
import Debug from '@substrate-system/debug'
8563

86-
// log b/c we are not calling with `false`
87-
const debug = Debug()
64+
// Set DEBUG in localStorage
65+
localStorage.setItem('DEBUG', 'myapp:*')
8866

89-
debug('hello')
67+
const debug = Debug('myapp:component')
68+
debug('hello logs')
69+
// will log, because DEBUG in localStorage matches 'myapp:*'
9070
```
9171

92-
You can use any variable as debug status:
72+
## Node JS
73+
Run your script with an env variable, `DEBUG`.
9374

9475
```js
95-
import Debug from '@substrate-system/debug'
96-
97-
// in Vite
98-
const debug = Debug(!!(import.meta.env && import.meta.env.DEV))
99-
100-
// in an arbitrary server
101-
const debug = Debug(window.EXAMPLE_DEBUG_MODE)
76+
// in node JS
77+
import createDebug from '@substrate-system/debug/node'
78+
const debug = createDebug('fooo')
79+
debug('testing')
10280
```
10381

104-
Use an env variable of `*` to log everything.
105-
106-
107-
### NODE_ENV + Vite
108-
109-
Build the site with a `NODE_ENV` variable to set `import.meta.env.DEV`:
110-
82+
Call this with an env var of `DEBUG=fooo`
11183
```sh
112-
NODE_ENV=development vite build
84+
DEBUG=fooo node ./test/fixture/node.js
11385
```
11486

115-
Any value of `NODE_ENV`, except `production`, wil equate to
116-
`import.meta.env.DEV` being true.
87+
## Config
11788

118-
```sh
119-
NODE_ENV=staging vite build
120-
```
89+
### Namespace
90+
In browsers, this checks `localStorage` for `DEBUG` key. In Node.js, this checks
91+
the environment variable `DEBUG`.
12192

122-
----------------------------------------------------------------------
93+
```js
94+
import Debug from '@substrate-system/debug'
12395

124-
## install
96+
// In browser: checks localStorage.getItem('DEBUG')
97+
const debug = Debug('example')
12598

126-
```sh
127-
npm i -D @substrate-system/debug
99+
// Log if no namespace is set in localStorage
100+
const debug = Debug(import.meta.env.DEV)
128101
```
129102
130-
Use this with [vite](https://vitejs.dev/) in the [browser](#browser), or
131-
in [node](#node-JS).
132-
133-
134-
------------------------------------------------------------------
135-
136-
137-
## Node JS
138-
Run your script with an env variable, `DEBUG`.
103+
### Enable all namespaces
139104
140105
```js
141-
// in node JS
142-
import createDebug from '@substrate-system/debug/node'
143-
const debug = createDebug('fooo')
144-
debug('testing')
106+
localStorage.setItem('DEBUG', '*')
145107
```
146108
147-
Call this with an env var of `DEBUG=fooo`
148-
```sh
149-
DEBUG=fooo node ./test/fixture/node.js
109+
### Enable specific namespaces
110+
```js
111+
localStorage.setItem('DEBUG', 'myapp:auth,myapp:api')
150112
```
151113
152-
### NODE_ENV
153-
If you are in dev mode (`process.env.NODE_ENV === 'development'`), then this will log things in a random color if you don't initialize it with a namespace --
114+
### Force logging with boolean true
115+
116+
You can also pass `true` to force logging regardless of `localStorage`.
117+
For example, in Vite, this will log on your localhost server, but not
118+
in production:
154119
155120
```js
156-
import createDebug from '@substrate-system/debug'
157-
const debug = createDebug()
158-
debug('hello')
121+
const debug = Debug(import.meta.env.DEV)
122+
debug('This logs')
159123
```
160124
161-
Run the script like this:
162-
```sh
163-
NODE_ENV=development node ./my-script.js
164-
```
125+
------------------------------------------------------------------
165126
166-
-------------------------------------------------------------------
167127
168-
## develop
128+
## Develop
169129
170130
### browser
171-
Start a `vite` server and log some things. This uses [the example directory](./example/).
131+
Start a `vite` server and log some things. This uses
132+
[the example directory](./example/).
172133
173134
```sh
174135
npm start
175136
```
176137
177138
178-
## test
139+
## Test
140+
141+
### Node
179142
180-
### node
181143
Run tests:
182144
183145
```sh

example/index.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,11 @@ debug7('hello quxxx')
3131
const debug8 = Debug('foo-bar')
3232

3333
debug8('hello eight')
34+
35+
// testing boolean true - should always log regardless of localStorage
36+
const debugForced = Debug(true)
37+
debugForced('This should always log because we passed boolean true!')
38+
39+
// testing boolean false - should return noop
40+
const debugNoop = Debug(false)
41+
debugNoop('This should never log because we passed boolean false!')

package.json

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,6 @@
4444
},
4545
"dependencies": {
4646
"@substrate-system/util": "^0.1.19",
47-
"ms": "2.1.3",
4847
"supports-color": "^10.0.0"
4948
},
5049
"devDependencies": {

src/browser/index.ts

Lines changed: 24 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -15,33 +15,32 @@ export default createDebug
1515
/**
1616
* Check if the given namespace is enabled.
1717
* `namespace` is the name that is passed into debug.
18-
* Need to check it against the env var.
18+
* `forcedEnabled` is a boolean that forces logging when true.
19+
* Only checks localStorage for the DEBUG key, unless forced.
1920
*/
20-
function isEnabled (
21-
namespace:string,
22-
env?:ImportMetaEnv|Record<string, string>
23-
):boolean {
21+
function isEnabled (namespace:string, forcedEnabled?:boolean):boolean {
22+
// If explicitly forced to be enabled via boolean true
23+
if (forcedEnabled === true) return true
24+
2425
const DEBUG = localStorage.getItem('DEBUG')
25-
if (
26-
(env && (env.VITE_DEBUG === '*' || env.DEBUG === '*')) ||
27-
DEBUG === '*'
28-
) return true
26+
27+
// Check for wildcard
28+
if (DEBUG === '*') return true
2929

3030
// if we were not called with a namespace
3131
if (namespace === 'DEV') {
3232
// We want to log iff there is no DEBUG variable.
33-
if (!env || (!env.VITE_DEBUG && !DEBUG)) {
33+
if (!DEBUG) {
3434
return true
3535
}
36-
3736
return false
3837
}
3938

40-
env = env || {}
39+
// No DEBUG variable set
40+
if (!DEBUG) return false
4141

42-
if (!DEBUG && (!env || (!env.VITE_DEBUG && !env.DEBUG))) return false
43-
const envVars = createRegexFromEnvVar(namespace)
44-
return envVars.some(regex => regex.test(env.VITE_DEBUG || env.DEBUG || DEBUG))
42+
const envVars = createRegexFromEnvVar(DEBUG)
43+
return envVars.some(regex => regex.test(namespace))
4544
}
4645

4746
/**
@@ -63,10 +62,10 @@ function logger (
6362
namespace:string,
6463
args:any[],
6564
{ prevTime, color },
66-
env?:Record<string, string>
65+
forcedEnabled?:boolean
6766
) {
6867
args = args || []
69-
if (!isEnabled(namespace, env)) return
68+
if (!isEnabled(namespace, forcedEnabled)) return
7069

7170
// Set `diff` timestamp
7271
const curr = Number(new Date())
@@ -153,7 +152,7 @@ function formatArgs ({ diff, color, namespace, useColors }:{
153152
(useColors ? ' %c' : ' ') +
154153
args[0] +
155154
(useColors ? '%c ' : ' ') +
156-
'+' + humanize(diff)
155+
'+' + humanize(diff, {})
157156

158157
if (!useColors) return
159158

@@ -182,20 +181,24 @@ function formatArgs ({ diff, color, namespace, useColors }:{
182181
return args
183182
}
184183

185-
function createDebug (namespace?:string|boolean, env?:Record<string, string>) {
184+
function createDebug (namespace?:string|boolean) {
186185
if (namespace === false) return noop
187186
const prevTime = Number(new Date())
188187
const color = selectColor(
189188
typeof namespace === 'string' ? namespace : generateRandomString(10),
190189
colors
191190
)
192191

192+
// Determine if this is a boolean true passed as the namespace
193+
const forcedEnabled = namespace === true
194+
const actualNamespace = typeof namespace === 'string' ? namespace : 'DEV'
195+
193196
const debug:(...args:any[])=>void = function (...args:any[]) {
194197
return logger(
195-
typeof namespace === 'string' ? namespace : 'DEV',
198+
actualNamespace,
196199
args,
197200
{ prevTime, color },
198-
env
201+
forcedEnabled
199202
)
200203
}
201204

0 commit comments

Comments
 (0)