Skip to content

Commit

Permalink
Merge pull request #177 from fullstack-build/development
Browse files Browse the repository at this point in the history
ESM & CJS + alternation of settings at runtime
  • Loading branch information
terehov authored Nov 22, 2022
2 parents bb0f230 + 6118748 commit 3631aa1
Show file tree
Hide file tree
Showing 13 changed files with 183 additions and 49 deletions.
52 changes: 44 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
🤓 **Stack trace and pretty errors**<br>
👨‍👧‍👦 **Sub logger with inheritance**<br>
🙊 **Mask/hide secrets and keys**<br>
📦 **ESM with tree shaking support**<br>
📦 **CJS & ESM with tree shaking support**<br>
✍️ **Well documented and tested**<br>

## Example
Expand All @@ -49,8 +49,6 @@ Donations help me allocate more time for my open source work.

## Install

> **`tslog` is a native ES module.**
```bash
npm install tslog
```
Expand Down Expand Up @@ -93,16 +91,26 @@ npm start

**Otherwise:**

Node.js with JavaScript:
ESM: Node.js with JavaScript:
```bash
node --enable-source-maps --experimental-specifier-resolution=node
```

Node.js with TypeScript and `ts-node` (with ESM support):
CJS: Node.js with JavaScript:
```bash
node --enable-source-maps
```

ESM: Node.js with TypeScript and `ts-node`:
```bash
node --enable-source-maps --experimental-specifier-resolution=node --no-warnings --loader ts-node/esm
```

CJS: Node.js with TypeScript and `ts-node`:
```bash
node --enable-source-maps --no-warnings --loader ts-node/cjs
```

Browser:
```html
<!doctype html>
Expand Down Expand Up @@ -252,6 +260,30 @@ A `settings` object is the first parameter passed to the `tslog` constructor:
const logger = new Logger<ILogObj>({ /* SETTINGS */ }, defaultLogObject);
```

##### Changing settings at runtime
`settings` is a public property and can also be changed on runtime.

Example on changing `minLevel` on runtime:

```typescript
const logger = new Logger({
minLevel: 1
});

// visible
logger.log(1, "level_one", "LOG1");
// visible
logger.log(2, "level_two", "LOG2");

// change minLevel to 2
logger.settings.minLevel = 2;

// hidden
logger.log(1, "level_one", "LOG3");
// visible
logger.log(2, "level_two", "LOG4");
```

#### Type: pretty, json, hidden

- `pretty` **Default setting** prints out a formatted structured "pretty" log entry.
Expand Down Expand Up @@ -298,9 +330,9 @@ secondSubLogger.silly("foo bar 2");

Output:
```bash
2022-11-17 10:45:47.705 SILLY [/examples/nodejs/index2.ts:51] MainLogger foo bar
2022-11-17 10:45:47.706 SILLY [/examples/nodejs/index2.ts:54] MainLogger:FirstSubLogger foo bar 1
2022-11-17 10:45:47.706 SILLY [/examples/nodejs/index2.ts:57] MainLogger:FirstSubLogger:SecondSubLogger foo bar 2
2022-11-17 10:45:47.705 SILLY [/examples/nodejs/index2.ts:51 MainLogger] foo bar
2022-11-17 10:45:47.706 SILLY [/examples/nodejs/index2.ts:54 MainLogger:FirstSubLogger ] foo bar 1
2022-11-17 10:45:47.706 SILLY [/examples/nodejs/index2.ts:57 MainLogger:FirstSubLogger:SecondSubLogger] foo bar 2
```

#### minLevel
Expand Down Expand Up @@ -356,6 +388,8 @@ Following settings are available for styling:
- `{{rawIsoStr}}`: Renders the date and time in ISO format (e.g.: YYYY-MM-DDTHH:mm:ss.SSSZ)
- `{{logLevelName}}`: name of the log level
- `{{name}}`: optional name of the current logger and his parents (e.g. "ParentLogger:ThisLogger")
- `{{nameWithDelimiterPrefix}}`: optional name of the current logger (s. above) with a delimiter in the beginning
- `{{nameWithDelimiterSuffix}}`: optional name of the current logger (s. above) with a delimiter at the end
- `{{fullFilePath}}`: a full path starting from `/` root
- `{{filePathWithLine}}`: a full path below the project path with line number
- `prettyErrorTemplate`: template string for error message. Possible placeholders:
Expand Down Expand Up @@ -407,6 +441,8 @@ const logger = new Logger({
dateIsoStr: "white",
filePathWithLine: "white",
name: ["white", "bold"],
nameWithDelimiterPrefix: ["white", "bold"],
nameWithDelimiterSuffix: ["white", "bold"],
errorName: ["bold", "bgRedBright", "whiteBright"],
fileName: ["yellow"],
},
Expand Down
23 changes: 12 additions & 11 deletions build.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { build } from "esbuild";
const esbuild = require("esbuild");

build({
entryPoints: ["src/index.ts"],
outfile: "dist/browser/index.js",
platform: "browser",
bundle: true,
minify: true,
format: "iife",
globalName: "tslog",
loader: { ".ts": "ts" },
})
esbuild
.build({
entryPoints: ["src/index.ts"],
outfile: "dist/browser/index.js",
platform: "browser",
bundle: true,
minify: true,
format: "iife",
globalName: "tslog",
loader: { ".ts": "ts" },
})
.then(() => console.log("⚡ Done"))
.catch(() => process.exit(1));
52 changes: 44 additions & 8 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
🤓 **Stack trace and pretty errors**<br>
👨‍👧‍👦 **Sub logger with inheritance**<br>
🙊 **Mask/hide secrets and keys**<br>
📦 **ESM with tree shaking support**<br>
📦 **CJS & ESM with tree shaking support**<br>
✍️ **Well documented and tested**<br>

## Example
Expand All @@ -49,8 +49,6 @@ Donations help me allocate more time for my open source work.

## Install

> **`tslog` is a native ES module.**
```bash
npm install tslog
```
Expand Down Expand Up @@ -93,16 +91,26 @@ npm start

**Otherwise:**

Node.js with JavaScript:
ESM: Node.js with JavaScript:
```bash
node --enable-source-maps --experimental-specifier-resolution=node
```

Node.js with TypeScript and `ts-node` (with ESM support):
CJS: Node.js with JavaScript:
```bash
node --enable-source-maps
```

ESM: Node.js with TypeScript and `ts-node`:
```bash
node --enable-source-maps --experimental-specifier-resolution=node --no-warnings --loader ts-node/esm
```

CJS: Node.js with TypeScript and `ts-node`:
```bash
node --enable-source-maps --no-warnings --loader ts-node/cjs
```

Browser:
```html
<!doctype html>
Expand Down Expand Up @@ -252,6 +260,30 @@ A `settings` object is the first parameter passed to the `tslog` constructor:
const logger = new Logger<ILogObj>({ /* SETTINGS */ }, defaultLogObject);
```

##### Changing settings at runtime
`settings` is a public property and can also be changed on runtime.

Example on changing `minLevel` on runtime:

```typescript
const logger = new Logger({
minLevel: 1
});

// visible
logger.log(1, "level_one", "LOG1");
// visible
logger.log(2, "level_two", "LOG2");

// change minLevel to 2
logger.settings.minLevel = 2;

// hidden
logger.log(1, "level_one", "LOG3");
// visible
logger.log(2, "level_two", "LOG4");
```

#### Type: pretty, json, hidden

- `pretty` **Default setting** prints out a formatted structured "pretty" log entry.
Expand Down Expand Up @@ -298,9 +330,9 @@ secondSubLogger.silly("foo bar 2");

Output:
```bash
2022-11-17 10:45:47.705 SILLY [/examples/nodejs/index2.ts:51] MainLogger foo bar
2022-11-17 10:45:47.706 SILLY [/examples/nodejs/index2.ts:54] MainLogger:FirstSubLogger foo bar 1
2022-11-17 10:45:47.706 SILLY [/examples/nodejs/index2.ts:57] MainLogger:FirstSubLogger:SecondSubLogger foo bar 2
2022-11-17 10:45:47.705 SILLY [/examples/nodejs/index2.ts:51 MainLogger] foo bar
2022-11-17 10:45:47.706 SILLY [/examples/nodejs/index2.ts:54 MainLogger:FirstSubLogger ] foo bar 1
2022-11-17 10:45:47.706 SILLY [/examples/nodejs/index2.ts:57 MainLogger:FirstSubLogger:SecondSubLogger] foo bar 2
```

#### minLevel
Expand Down Expand Up @@ -356,6 +388,8 @@ Following settings are available for styling:
- `{{rawIsoStr}}`: Renders the date and time in ISO format (e.g.: YYYY-MM-DDTHH:mm:ss.SSSZ)
- `{{logLevelName}}`: name of the log level
- `{{name}}`: optional name of the current logger and his parents (e.g. "ParentLogger:ThisLogger")
- `{{nameWithDelimiterPrefix}}`: optional name of the current logger (s. above) with a delimiter in the beginning
- `{{nameWithDelimiterSuffix}}`: optional name of the current logger (s. above) with a delimiter at the end
- `{{fullFilePath}}`: a full path starting from `/` root
- `{{filePathWithLine}}`: a full path below the project path with line number
- `prettyErrorTemplate`: template string for error message. Possible placeholders:
Expand Down Expand Up @@ -407,6 +441,8 @@ const logger = new Logger({
dateIsoStr: "white",
filePathWithLine: "white",
name: ["white", "bold"],
nameWithDelimiterPrefix: ["white", "bold"],
nameWithDelimiterSuffix: ["white", "bold"],
errorName: ["bold", "bgRedBright", "whiteBright"],
fileName: ["yellow"],
},
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 14 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "tslog",
"version": "4.1.0",
"version": "4.3.0-0",
"description": "📝 Extensible TypeScript Logger for Node.js and Browser: Dependency free, Fully customizable, Pretty errors, stack traces, and JSON output to attachable transports.",
"author": "Eugene <[email protected]> (http://fullstack.build/)",
"license": "MIT",
Expand All @@ -13,18 +13,25 @@
"bugs": {
"url": "https://github.com/fullstack-build/tslog/issues"
},
"main": "./dist/nodejs/index.js",
"main": "./dist/nodejs/cjs/index.js",
"module": "./dist/nodejs/esm/index.js",
"types": "./dist/nodejs/types/index.d.ts",
"browser": {
"tslog": "./dist/browser/index.js",
"util": "",
"util": false,
"./src/runtime/nodejs/index.ts": "./src/runtime/browser/index.ts"
},
"type": "module",
"exports": "./dist/nodejs/index.js",
"exports": {
".": {
"require": "./dist/nodejs/cjs/index.js",
"import": "./dist/nodejs/esm/index.js"
}
},
"scripts": {
"build": "npm run build-server && npm run build-browser",
"build": "npm run build-types && npm run build-server && npm run build-browser",
"build-browser": "node build.js",
"build-server": "tsc -b tsconfig.src.json",
"build-types": "tsc -b tsconfig.types.json",
"build-server": "tsc -b tsconfig.esm.json tsconfig.cjs.json",
"start": "node --enable-source-maps --experimental-specifier-resolution=node examples/dist/examples/nodejs/index2.js",
"dev-ts": "nodemon --watch './**/*.ts' --exec 'node --enable-source-maps --experimental-specifier-resolution=node --no-warnings --loader ts-node/esm' examples/nodejs/index2.ts",
"dev-ts-old-example": "nodemon --watch './**/*.ts' --exec 'node --enable-source-maps --experimental-specifier-resolution=node --no-warnings --loader ts-node/esm' examples/nodejs/index.ts",
Expand Down
19 changes: 13 additions & 6 deletions src/BaseLogger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ export * from "./interfaces";

export class BaseLogger<LogObj> {
private readonly runtime: "browser" | "nodejs" | "unknown";
private readonly settings: ISettings<LogObj>;
private subLoggers: BaseLogger<LogObj>[] = [];
public settings: ISettings<LogObj>;
// not needed yet
//private subLoggers: BaseLogger<LogObj>[] = [];

constructor(settings?: ISettingsParam<LogObj>, private logObj?: LogObj, private stackDepthLevel: number = 4) {
const isBrowser = ![typeof window, typeof document].includes("undefined");
Expand All @@ -24,7 +25,8 @@ export class BaseLogger<LogObj> {
minLevel: settings?.minLevel ?? 0,
argumentsArrayName: settings?.argumentsArrayName,
prettyLogTemplate:
settings?.prettyLogTemplate ?? "{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}}\t{{logLevelName}}\t[{{filePathWithLine}}]\t{{name}}",
settings?.prettyLogTemplate ??
"{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}}\t{{logLevelName}}\t[{{filePathWithLine}}{{nameWithDelimiterPrefix}}]\t",
prettyErrorTemplate: settings?.prettyErrorTemplate ?? "\n{{errorName}} {{errorMessage}}\nerror stack:\n{{errorStack}}",
prettyErrorStackTemplate: settings?.prettyErrorTemplate ?? " • {{fileName}}\t{{method}}\n\t{{filePathWithLine}}",
prettyErrorParentNamesSeparator: settings?.prettyErrorParentNamesSeparator ?? ":",
Expand All @@ -44,6 +46,8 @@ export class BaseLogger<LogObj> {
dateIsoStr: "white",
filePathWithLine: "white",
name: ["white", "bold"],
nameWithDelimiterPrefix: ["white", "bold"],
nameWithDelimiterSuffix: ["white", "bold"],
errorName: ["bold", "bgRedBright", "whiteBright"],
fileName: ["yellow"],
},
Expand Down Expand Up @@ -172,7 +176,7 @@ export class BaseLogger<LogObj> {
logObj?: LogObj,
stackDepthLevel?: number
) => this)(subLoggerSettings, this.logObj, this.stackDepthLevel);
this.subLoggers.push(subLogger);
//this.subLoggers.push(subLogger);
return subLogger;
}

Expand Down Expand Up @@ -290,8 +294,11 @@ export class BaseLogger<LogObj> {
// name
let parentNamesString = this.settings.parentNames?.join(this.settings.prettyErrorParentNamesSeparator);
parentNamesString = parentNamesString != null && logObjMeta?.name != null ? parentNamesString + this.settings.prettyErrorParentNamesSeparator : undefined;
const nameStr = logObjMeta?.name != null || parentNamesString != null ? (parentNamesString ?? "") + logObjMeta?.name ?? "" : "";
placeholderValues["name"] = nameStr.length > 0 ? nameStr + this.settings.prettyErrorLoggerNameDelimiter : "";
placeholderValues["name"] = logObjMeta?.name != null || parentNamesString != null ? (parentNamesString ?? "") + logObjMeta?.name ?? "" : "";
placeholderValues["nameWithDelimiterPrefix"] =
placeholderValues["name"].length > 0 ? this.settings.prettyErrorLoggerNameDelimiter + placeholderValues["name"] : "";
placeholderValues["nameWithDelimiterSuffix"] =
placeholderValues["name"].length > 0 ? placeholderValues["name"] + this.settings.prettyErrorLoggerNameDelimiter : "";

return formatTemplate(this.settings, template, placeholderValues);
}
Expand Down
9 changes: 9 additions & 0 deletions src/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,15 @@ export interface ISettingsParam<LogObj> {
ms?: TStyle;
dateIsoStr?: TStyle;
logLevelName?: TStyle;
fileName?: TStyle;
filePath?: TStyle;
fileLine?: TStyle;
filePathWithLine?: TStyle;
name?: TStyle;
nameWithDelimiterPrefix?: TStyle;
nameWithDelimiterSuffix?: TStyle;
errorName?: TStyle;
errorMessage?: TStyle;
};
prettyInspectOptions?: InspectOptions;
metaProperty?: string;
Expand Down Expand Up @@ -82,6 +89,8 @@ export interface ISettings<LogObj> extends ISettingsParam<LogObj> {
fileLine?: TStyle;
filePathWithLine?: TStyle;
name?: TStyle;
nameWithDelimiterPrefix?: TStyle;
nameWithDelimiterSuffix?: TStyle;
errorName?: TStyle;
errorMessage?: TStyle;
};
Expand Down
Loading

0 comments on commit 3631aa1

Please sign in to comment.