Skip to content

Commit 6b98e17

Browse files
authored
4.10.0 (#320) (#321)
* 4.10.0 (#320) * New version 4.10.0 * Update CI configuration, remove husky pre-commit, and add simple-git-hooks; introduce Jest configuration and TypeScript settings * Add prepare-publish script and update build process in package.json * Fix path in np configuration to remove leading dot in contents * Add pre-commit hook script to manage pre-commit tasks * 4.10.0 * Revert version number to 4.9.3 in package.json * 4.10.0 * Enhance pre-commit hook to check for npm availability and update package.json paths * Refactor pre-commit hook to remove npm availability check * 4.10.1 * Fix CJS build, add README to dist folder * 4.10.2 * Add CI-specific launch arguments for Puppeteer
1 parent 9a5d156 commit 6b98e17

File tree

81 files changed

+12894
-18273
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

81 files changed

+12894
-18273
lines changed

.eslintrc.json

Lines changed: 0 additions & 28 deletions
This file was deleted.

.github/workflows/ci.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,11 @@ jobs:
1212

1313
strategy:
1414
matrix:
15-
node-version: [16.x, 18.x]
15+
node-version: [20.x]
1616

1717
env:
1818
CI: true
19-
COVERAGE: ${{ matrix.node-version == '18.x' && true || false }}
19+
COVERAGE: ${{ matrix.node-version == '20.x' && true || false }}
2020

2121
steps:
2222
- uses: actions/checkout@v3

.husky/pre-commit

Lines changed: 0 additions & 8 deletions
This file was deleted.

CHANGELOG.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Changelog
2+
3+
## [4.10.0] - 2025-09-25
4+
5+
### Breaking
6+
- Custom `transportFormatted` overrides now receive `logMeta` as the fourth argument; pass five parameters to also receive `settings`, otherwise adjust implementations that previously read `settings` from the fourth position.
7+
- Deprecated runtime entry points under `src/runtime/**` and related browser mappings have been removed; use the primary `Logger` export instead of importing runtime-specific helpers.
8+
- Logger metadata now exposes lowercase runtime identifiers (for example `node`, `browser`, `deno`, `bun`, `worker`) and normalized versions without the leading `v`; adjust consumers that compared against `Nodejs` or relied on the old format.
9+
10+
### Added
11+
- Introduced universal runtime detection that recognises Node.js, browsers, web workers, Deno, and Bun, enriching metadata with runtime versions and hostnames when available.
12+
- Documented first-class Deno and Bun usage, refreshed examples under `examples/server`, and aligned development scripts (`npm run dev-ts*`).
13+
- Pretty transports now detect when the browser console supports CSS, rendering styled output with `%c` tokens and gracefully falling back when styling is unavailable.
14+
- Error formatting captures chained `Error.cause` entries (up to depth five) and includes them in both pretty error blocks and JSON error objects.
15+
16+
### Changed
17+
- The core logger automatically locates the first user stack frame instead of relying on hard-coded depths, producing stable file and line metadata across bundlers; manual `stackDepthLevel` overrides continue to work.
18+
- Placeholder formatting now routes through a shared `buildPrettyMeta` utility, improving consistency for custom templates and nested style tokens.
19+
- Masking internals normalise and cache case-insensitive keys, reducing repeated allocations and keeping behaviour consistent when toggling mask options.
20+
- Browser styling defaults keep ANSI colouring enabled unless explicitly disabled, letting CSS-capable consoles honour `stylePrettyLogs` without runtime-specific tweaks.
21+
22+
### Fixed
23+
- Runtime error detection now treats objects with an `Error`-suffixed name as errors, ensuring they are formatted via the error transport.
24+
- Browser stack parsing guards against malformed frames, avoiding crashes when devtools emit unexpected stack entries.
25+
- Logging no longer fails when `process.cwd()` throws (for example under restricted permissions); environment helpers fall back to cached working directories and hostname detection across Node, Deno, and Bun.

README.md

Lines changed: 57 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919

2020
**Fast and powerful**<br>
2121
🪶 **Lightweight and flexible**<br>
22-
🏗 **Universal: Works in Browsers and Node.js**<br>
22+
🏗 **Universal: Works in Browsers, Node.js, Deno and Bun**<br>
2323
👮‍️ **Fully typed with TypeScript support (native source maps)**<br>
2424
🗃 **_Pretty_ or `JSON` output**<br>
2525
📝 **Customizable log level**<br>
@@ -53,62 +53,65 @@ Donations help me allocate more time for my open source work.
5353
npm install tslog
5454
```
5555

56-
In order to run a native ES module in Node.js, you have to do two things:
56+
### Node.js
5757

58-
1) Set `"type": "module"` in `package.json`.
59-
2) For now, start with `--experimental-specifier-resolution=node`
58+
Enable native ESM by setting `"type": "module"` and run Node with source maps for accurate stack traces:
6059

61-
Example `package.json`
6260
```json5
6361
{
6462
"name": "NAME",
6563
"version": "1.0.0",
66-
"main": "index.js",
67-
// here:
6864
"type": "module",
6965
"scripts": {
7066
"build": "tsc -p .",
71-
// and here:
72-
"start": "node --enable-source-maps --experimental-specifier-resolution=node index.js"
67+
"start": "node --enable-source-maps dist/index.js"
7368
},
7469
"dependencies": {
7570
"tslog": "^4"
76-
},
77-
"devDependencies": {
78-
"typescript": "^4"
79-
},
80-
"engines": {
81-
"node": ">=16"
8271
}
8372
}
8473
```
8574

86-
With this `package.json` you can simply build and run it:
75+
After building (`npm run build`), start your app with:
76+
8777
```bash
88-
npm run build
8978
npm start
9079
```
9180

92-
**Otherwise:**
81+
Other handy entry points:
9382

94-
ESM: Node.js with JavaScript:
95-
```bash
96-
node --enable-source-maps --experimental-specifier-resolution=node
83+
- `node --enable-source-maps dist/index.cjs` – run the CommonJS bundle.
84+
- `node --enable-source-maps --loader ts-node/esm src/index.ts` – execute TypeScript via `ts-node` in ESM mode.
85+
- `node --enable-source-maps --require ts-node/register src/index.ts` – execute TypeScript via `ts-node` in CommonJS mode.
86+
87+
### Deno
88+
89+
```ts
90+
// main.ts
91+
import { Logger } from "npm:tslog";
92+
93+
const logger = new Logger();
94+
logger.info("Hello from Deno");
9795
```
9896

99-
CJS: Node.js with JavaScript:
10097
```bash
101-
node --enable-source-maps
98+
deno run main.ts
99+
# grant optional metadata access: deno run --allow-env main.ts
102100
```
103101

104-
ESM: Node.js with TypeScript and `ts-node`:
105-
```bash
106-
node --enable-source-maps --experimental-specifier-resolution=node --no-warnings --loader ts-node/esm
102+
### Bun
103+
104+
```ts
105+
// main.ts
106+
import { Logger } from "tslog";
107+
108+
const logger = new Logger();
109+
logger.info("Hello from Bun");
107110
```
108111

109-
CJS: Node.js with TypeScript and `ts-node`:
110112
```bash
111-
node --enable-source-maps --no-warnings --loader ts-node/cjs
113+
bun run main.ts
114+
# or add "dev": "bun run src/main.ts" to package.json scripts
112115
```
113116

114117
Browser:
@@ -166,7 +169,7 @@ logger.fatal(new Error("I am a pretty Error with a stacktrace."));
166169

167170
## All Features
168171

169-
- **Universal:** Works in browsers and Node.js
172+
- **Universal:** Works in browsers, Node.js, Deno, and Bun
170173
- **Tested:** Great code coverage, CI
171174
- **Super customizable:** Every aspect can be overwritten
172175
- **Fully typed:** Written in TypeScript, with native TypeScript support
@@ -240,7 +243,7 @@ In addition to the default log level, custom log level can be defined in the sam
240243
> **Tip:** Also the generic logging method (log()) returns a _JSON_ representation of the log message (`ILogObject`).
241244
242245
```typescript
243-
import { BaseLogger, ILogObjMeta, ISettingsParam, ILogObj } from "./BaseLogger";
246+
import { BaseLogger, ILogObjMeta, ISettingsParam, ILogObj } from "tslog";
244247

245248
export class CustomLogger<LogObj> extends BaseLogger<LogObj> {
246249
constructor(settings?: ISettingsParam<LogObj>, logObj?: LogObj) {
@@ -371,9 +374,9 @@ secondSubLogger.silly("foo bar 2");
371374

372375
Output:
373376
```bash
374-
2022-11-17 10:45:47.705 SILLY [/examples/nodejs/index2.ts:51 MainLogger] foo bar
375-
2022-11-17 10:45:47.706 SILLY [/examples/nodejs/index2.ts:54 MainLogger:FirstSubLogger ] foo bar 1
376-
2022-11-17 10:45:47.706 SILLY [/examples/nodejs/index2.ts:57 MainLogger:FirstSubLogger:SecondSubLogger] foo bar 2
377+
2022-11-17 10:45:47.705 SILLY [/examples/server/index2.ts:51 MainLogger] foo bar
378+
2022-11-17 10:45:47.706 SILLY [/examples/server/index2.ts:54 MainLogger:FirstSubLogger ] foo bar 1
379+
2022-11-17 10:45:47.706 SILLY [/examples/server/index2.ts:57 MainLogger:FirstSubLogger:SecondSubLogger] foo bar 2
377380
```
378381

379382
#### minLevel
@@ -455,8 +458,8 @@ Following settings are available for styling:
455458
- `prettyInspectOptions`: <a href="https://nodejs.org/api/util.html#utilinspectobject-options" target="_blank">Available options</a>
456459

457460
### Customizing template tokens
458-
It's possible to add user defined tokes, by overwriting the `addPlaceholders` in the `settings.overwrite`. this callback allows to add or overwrite tokens in the `placeholderValues`.
459-
for example, to add the token: `{{custom}}`;
461+
You can add your own template tokens by overriding `settings.overwrite.addPlaceholders`. The callback receives the current metadata object and the placeholder map so you can add or overwrite entries.
462+
For example, to add the token `{{custom}}`:
460463
```javascript
461464
const logger = new Logger({
462465
type: "pretty",
@@ -468,10 +471,10 @@ Following settings are available for styling:
468471
},
469472
});
470473
```
471-
this would yield in the token `{{custom}}` being replaced with `"test"`
474+
This replaces `{{custom}}` with the string `"test"` in the rendered output.
472475

473476
- **Styling:**
474-
- `stylePrettyLogs`: defines whether logs should be styled and colorized
477+
- `stylePrettyLogs`: defines whether logs should be styled and colorized (ANSI in server runtimes, CSS in browsers that support it)
475478
- `prettyLogStyles`: provides colors and styles for different placeholders and can also be dependent on the value (e.g. log level)
476479
- Level 1: template placeholder (defines a style for a certain template placeholder, s. above, without brackets).
477480
- Level 2: Either a string with one style (e.g. `white`), or an array of styles (e.g. `["bold", "white"]`), or a nested object with key being a value.
@@ -485,6 +488,8 @@ Following settings are available for styling:
485488
`tslog` collects meta information for every log, like runtime, code position etc. The meta information collected depends on the runtime (browser or Node.js) and is accessible through the `LogObj`.
486489
You can define the property containing this meta information with `metaProperty`, which is "_meta" by default.
487490

491+
`tslog` automatically determines the first caller frame outside of the library, even in bundled environments such as Vite or Next.js. If you need to override the detected frame, provide `stackDepthLevel` when constructing a `Logger`.
492+
488493
#### Pretty templates and styles (color settings)
489494

490495
```typescript
@@ -676,13 +681,21 @@ For `pretty` logs:
676681
formatLogObj: <LogObj>(maskedArgs: unknown[], settings: ISettings<LogObj>) => {
677682
// format LogObj attributes to a string and return it
678683
},
679-
transportFormatted: (logMetaMarkup: string, logArgs: unknown[], logErrors: string[], settings: unknown) => {
684+
transportFormatted: (
685+
logMetaMarkup: string,
686+
logArgs: unknown[],
687+
logErrors: string[],
688+
logMeta?: IMeta,
689+
settings?: ISettings<LogObj>
690+
) => {
680691
// overwrite the default transport for formatted (e.g. pretty) log levels. e.g. replace console with StdOut, write to file etc.
681692
},
682693
},
683694
});
684695
```
685696

697+
> **Note:** `transportFormatted` receives the resolved log meta as an optional fourth argument and the active settings as an optional fifth argument. Handlers that still accept only three arguments continue to work unchanged.
698+
686699
For `JSON` logs (no formatting happens here):
687700
```typescript
688701
const logger = new Logger({
@@ -701,9 +714,9 @@ For `JSON` logs (no formatting happens here):
701714
const logger = new Logger({
702715
type: "pretty",
703716
overwrite: {
704-
transportFormatted: (logMetaMarkup, logArgs, logErrors) => {
717+
transportFormatted: (logMetaMarkup, logArgs, logErrors, logMeta) => {
705718
// Send different log levels to appropriate console methods
706-
const logLevel = logMetaMarkup.trim().split("\t")[1]; // Extract log level from the markup
719+
const logLevel = logMeta?.logLevelName ?? logMetaMarkup.trim().split("\t")[1];
707720
switch (logLevel) {
708721
case "WARN":
709722
console.warn(logMetaMarkup, ...logArgs, ...logErrors);
@@ -749,18 +762,18 @@ const logMsg = logger.info("Test");
749762
// '0': 'Test',
750763
// foo: 'bar',
751764
// _meta: {
752-
// runtime: 'Nodejs',
765+
// runtime: 'server',
753766
// hostname: 'Eugenes-MBP.local',
754767
// date: 2022-10-23T10:51:08.857Z,
755768
// logLevelId: 3,
756769
// logLevelName: 'INFO',
757770
// path: {
758-
// fullFilePath: 'file:///[...]/tslog/examples/nodejs/index.ts:113:23',
771+
// fullFilePath: 'file:///[...]/tslog/examples/server/index.ts:113:23',
759772
// fileName: 'index.ts',
760773
// fileColumn: '23',
761774
// fileLine: '113',
762-
// filePath: '/examples/nodejs/index.ts',
763-
// filePathWithLine: '/examples/nodejs/index.ts:113'
775+
// filePath: '/examples/server/index.ts',
776+
// filePathWithLine: '/examples/server/index.ts:113'
764777
// }
765778
// }
766779
//}

0 commit comments

Comments
 (0)