Skip to content

Commit af852e6

Browse files
authored
Merge pull request #18 from willybrauner/add-elapsed-time
feat: Add elapsed time
2 parents c9285a9 + eb041fa commit af852e6

6 files changed

Lines changed: 110 additions & 65 deletions

File tree

examples/browser/package.json

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,9 @@
11
{
22
"name": "browser",
3-
"version": "1.0.0",
4-
"description": "",
5-
"main": "index.js",
63
"scripts": {
74
"dev": "vite --host",
85
"build": "vite build"
96
},
10-
"keywords": [],
11-
"author": "",
12-
"license": "ISC",
137
"dependencies": {
148
"@wbe/debug": "workspace:*"
159
},

examples/browser/src/index.ts

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,32 @@
11
import { menu } from "./Menu"
22
import debug, { couleur } from "@wbe/debug"
3+
;(async () => {
4+
const log = debug("front:index")
5+
log("index log", { props: "foo" })
36

4-
const log = debug("front:index")
7+
for (let i = 0; i < 10; i++) {
8+
await new Promise((resolve) =>
9+
setTimeout(resolve, 100 * Math.random() + 100 / 100)
10+
)
11+
debug(`front:${i + "-test"}`)(`index log ${i}`)
12+
}
13+
debug(`front:others-types`)(
14+
`new log`,
15+
[
16+
{ name: "foo", value: "bar" },
17+
{ name: "bar", value: "foo" },
18+
{ name: "baz", value: "qux" },
19+
{ name: "qux", value: "baz" },
20+
],
21+
null,
22+
undefined,
23+
"foo"
24+
)
25+
menu()
526

6-
log("index log", { props: "foo" })
7-
log("test 2")
27+
console.log("native console log (should be removed by esbuild in production)")
828

9-
console.log(couleur.bold("native console log: hello bold"))
10-
menu()
29+
for (let i = 0; i < 3; i++) {
30+
console.log("native console log", i)
31+
}
32+
})()

examples/browser/tsconfig.json

Lines changed: 1 addition & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,10 @@
11
{
22
"compilerOptions": {
3-
"module": "commonjs",
3+
"module": "esnext",
44
"target": "esnext",
5-
"outDir": "dist",
6-
"rootDir": "../../",
7-
"composite": false,
8-
"lib": ["dom", "es2015"],
95
"moduleResolution": "node",
106
"types": ["node"],
11-
"declaration": true,
12-
"noImplicitAny": false,
13-
"esModuleInterop": true,
14-
"preserveConstEnums": true,
15-
"strictNullChecks": false,
16-
"skipLibCheck": true,
17-
"allowSyntheticDefaultImports": true,
18-
"strict": true,
19-
"sourceMap": true,
20-
"resolveJsonModule": true,
21-
"noEmit": true,
22-
"noUnusedLocals": true,
23-
"noUnusedParameters": true,
24-
"noImplicitReturns": true
257
},
26-
"include": ["./","../../dist"]
278
}
289

2910

package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
"import": "./dist/index.js"
1212
}
1313
},
14+
"types": "./dist/index.d.ts",
1415
"sideEffects": false,
1516
"repository": {
1617
"type": "git",
@@ -56,7 +57,7 @@
5657
{
5758
"name": "@wbe/debug",
5859
"path": "dist/index.js",
59-
"limit": "500 B"
60+
"limit": "600 B"
6061
}
6162
],
6263
"packageManager": "pnpm@9.14.2+sha512.6e2baf77d06b9362294152c851c4f278ede37ab1eba3a55fda317a4a17b209f4dbb973fb250a77abc463a341fcb1f17f17cfa24091c4eb319cda0d9b84278387"

src/debug.ts

Lines changed: 78 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,85 @@
11
import { couleur } from "./couleur"
22
import { isBrowser, stringToRgb } from "./helpers"
33

4+
let LAST_TIME = Date.now()
5+
46
/**
57
* debug
8+
* @param namespace - The namespace to log
9+
* @returns A function that logs the namespace and arguments to the console
10+
*
11+
* ex:
12+
* import debug from "@wbe/debug"
13+
* const log = debug("myNamespace")
14+
* log("Hello World") // logs "myNamespace Hello World +0ms"
615
*/
7-
// prettier-ignore
8-
export const debug = (namespace?: string) => (...rest: any[]): void => {
9-
const rgb = stringToRgb(namespace)
10-
11-
const showLog = (value: string): boolean =>
12-
value?.includes(":*")
13-
? namespace.startsWith( value.split(":*")[0])
14-
: value === namespace || value === "*"
15-
16-
// Allow to bypass dropping of console.log from the build process
17-
// tested with esbuild config: pure: ["console.log"] or drop: ["console"]
18-
const log = console['log']
19-
20-
if (isBrowser)
21-
{
22-
showLog(localStorage.getItem("debug"))
23-
&&
24-
log(
25-
namespace && `%c${namespace}`, `color: rgb(${rgb[0]}, ${rgb[1]}, ${rgb[2]})`,
26-
...rest
27-
)
28-
}
29-
30-
else
31-
{
32-
showLog(process.env.DEBUG)
33-
&&
34-
log(
35-
namespace && couleur.bold(couleur.rgb(rgb[0], rgb[1], rgb[2])(namespace)),
36-
...rest
37-
)
16+
export const debug =
17+
(namespace?: string, elapsedTime = true) =>
18+
(...rest: any[]): void => {
19+
// Calculate elapsed time since last execution
20+
const now = Date.now()
21+
const elapsed = now - LAST_TIME
22+
LAST_TIME = now
23+
const elapsedString = `+${elapsed}ms`
24+
25+
// Get the namespace color
26+
const rgb = stringToRgb(namespace)
27+
28+
// Define when to show the log
29+
const showLog = (value: string): boolean =>
30+
value?.includes(":*")
31+
? namespace.startsWith(value.split(":*")[0])
32+
: value === namespace || value === "*"
33+
34+
// Allow to bypass dropping of console.log from the build process
35+
// has been test with esbuild drop: ["console"] & pure: ["console.log"]
36+
const log = console["log"]
37+
38+
/**
39+
* Browser environment
40+
*/
41+
if (isBrowser) {
42+
if (showLog(localStorage.getItem("debug"))) {
43+
const colorStyle = `color: rgb(${rgb[0]}, ${rgb[1]}, ${rgb[2]}); font-weight: bold`
44+
const args = []
45+
46+
// Start with the colored namespace format specifier and its style
47+
let format = `%c${namespace}`
48+
args.push(colorStyle)
49+
50+
// Process the rest arguments
51+
// Use %c for strings to allow potential future styling or just display
52+
// Use %o for objects, arrays, etc., for better inspection
53+
for (let i = 0; i < rest.length; i++) {
54+
const arg = rest[i]
55+
if (typeof arg === "string") {
56+
format += ` %c${arg}`
57+
args.push("color: inherit")
58+
} else {
59+
format += " %o"
60+
args.push(arg)
61+
}
62+
}
63+
// Append the elapsed time format specifier and its style
64+
if (elapsedTime) {
65+
format += ` %c${elapsedString}`
66+
args.push(colorStyle)
67+
}
68+
// Append the whole formatted string and log it
69+
args.unshift(format)
70+
log(...args)
71+
}
72+
} else {
73+
/**
74+
* Node.js environment
75+
*/
76+
const wColor = (s: string) =>
77+
couleur.bold(couleur.rgb(rgb[0], rgb[1], rgb[2])(s))
78+
79+
if (showLog(process.env.DEBUG)) {
80+
elapsedTime
81+
? log(wColor(namespace), ...rest, wColor(elapsedString))
82+
: log(wColor(namespace), ...rest)
83+
}
84+
}
3885
}
39-
}

test/debug.test.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,8 @@ describe("debug", () => {
7777
expect(consoleLogCalls.length).toBe(1)
7878
})
7979

80-
it("should log multiple arguments correctly", () => {
80+
it("should log multiple arguments correctly", async () => {
81+
await new Promise((resolve) => setTimeout(resolve, 1000))
8182
process.env.DEBUG = "test-namespace"
8283
const testDebug = debug("test-namespace")
8384
testDebug("First argument", "Second argument", { key: "value" }, 123)

0 commit comments

Comments
 (0)