Skip to content

Commit

Permalink
Relaxing Context type for better DX (#71)
Browse files Browse the repository at this point in the history
  • Loading branch information
PetrHeinz authored Aug 11, 2023
1 parent de52a33 commit 20a6b79
Show file tree
Hide file tree
Showing 7 changed files with 44 additions and 23 deletions.
23 changes: 17 additions & 6 deletions example-project/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,14 @@ const logger = new Logtail(process.argv[2], { sendLogsToConsoleOutput: true });
// Usage

// Send debug level log using the debug() method
logger.debug("I am using Logtail!");
const debugLog = logger.debug("I am using Logtail!");

// Send info level log using the info() method
logger.info("An interesting event occured!")
const infoLog = logger.info("An interesting event occured!");

// Send warn level log using the warn() method
// You can add additional structured data to help you troubleshoot your code as shown below
logger.warn("Something is not quite right, better check on it.",{
const warningLog = logger.warn("Something is not quite right, better check on it.",{
user:{
username:"someuser",
email:"[email protected]"
Expand All @@ -36,9 +36,20 @@ logger.warn("Something is not quite right, better check on it.",{
}
});

// Send error level log using the error() method
logger.error("Oops! An runtime ERROR occurred!").then(
// Logging methods are async function returning Promises
function callbackThatMightFail() {
throw new Error("Testing error")
}

let errorLog;
try {
callbackThatMightFail();
} catch (err) {
// Send error level log using the error() method
errorLog = logger.error("Oops! An runtime ERROR occurred!", err);
}

// Logging methods are async function returning Promises
Promise.all([debugLog, infoLog, warningLog, errorLog]).then(
// OnResolve write message
function() {
console.log("All done! You can check your logs now.")
Expand Down
7 changes: 3 additions & 4 deletions packages/bunyan/src/bunyan.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import bunyan, { LogLevelString } from "bunyan";
import { Logtail } from "@logtail/node";
import {Context, LogLevel} from "@logtail/types";
import { LogLevel } from "@logtail/types";

import { LogtailStream } from "./bunyan";

Expand Down Expand Up @@ -130,9 +130,8 @@ describe("Bunyan tests", () => {
it("should include correct context fields", async done => {
const logtail = new Logtail("test");
logtail.setSync(async logs => {
const context = logs[0].context as Context;
const runtime = context.runtime as Context;
expect(runtime.file).toMatch("bunyan.test.ts")
const context = logs[0].context;
expect(context.runtime.file).toMatch("bunyan.test.ts")
done();
return logs;
});
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/base.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ describe("base class tests", () => {
expect(log.message).toBe(message);

// Context should contain a stack trace
expect((log as any).stack).toBe(e.stack);
expect(log.stack).toBe(e.stack);
});

it("should not ignore exceptions if `ignoreExceptions` opt == false and `throwExceptions` opt == true", async () => {
Expand Down
14 changes: 13 additions & 1 deletion packages/node/src/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,10 @@ export class Node extends Base {
const wrappedContext: unknown = { extra: context };
context = wrappedContext as TContext;
}
if (context instanceof Error) {
const wrappedContext: unknown = { error: context };
context = wrappedContext as TContext;
}

// Process/sync the log, per `Base` logic
context = { ...getStackContext(this, stackContextHint), ...context };
Expand Down Expand Up @@ -108,6 +112,12 @@ export class Node extends Base {
}

return value.toISOString();
} else if (value instanceof Error) {
return {
name: value.name,
message: value.message,
stack: value.stack?.split("\n"),
};
} else if ((typeof value === "object" || Array.isArray(value)) && (maxDepth < 1 || visitedObjects.has(value))) {
if (visitedObjects.has(value)) {
if (this._options.contextObjectCircularRefWarn) {
Expand Down Expand Up @@ -143,8 +153,10 @@ export class Node extends Base {
visitedObjects.delete(value);

return logClone;
} else {
} else if (typeof value === 'undefined') {
return undefined;
} else {
return `<omitted unserializable ${typeof value}>`;
}
}
}
8 changes: 4 additions & 4 deletions packages/types/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,10 +131,10 @@ We call this 'context' and these are the types:

```typescript
/**
* Context type - a string/number/bool/Date, or a nested object of the same
* Context type - a nested object of serializable types (a string / number / bool / null / undefined / Array / Date / Error)
*/
export type ContextKey = string | number | boolean | Date;
export type Context = { [key: string]: ContextKey | Context };
export type ContextKey = any;
export type Context = { [key: string]: ContextKey };
```

### `ILogtailLog`
Expand All @@ -146,7 +146,7 @@ interface ILogtailLog {
dt: Date;
level: LogLevel; // <-- see `LogLevel` above
message: string;
[key: string]: ContextKey | Context; // <-- see `Context` above
[key: string]: ContextKey; // <-- see `Context` above
}
```

Expand Down
8 changes: 4 additions & 4 deletions packages/types/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,10 +98,10 @@ export enum LogLevel {
}

/**
* Context type - a string/number/bool/Date, or a nested object of the same
* Context type - a nested object of serializable types (a string / number / bool / null / undefined / Array / Date / Error)
*/
export type ContextKey = string | number | boolean | Date | null;
export type Context = { [key: string]: ContextKey | Context };
export type ContextKey = any;
export type Context = { [key: string]: ContextKey };
export type StackContextHint = { fileName: string, methodNames: [string] };

/**
Expand All @@ -111,7 +111,7 @@ export interface ILogtailLog {
dt: Date;
level: ILogLevel;
message: string;
[key: string]: ContextKey | Context;
[key: string]: ContextKey;
}

/**
Expand Down
5 changes: 2 additions & 3 deletions packages/winston/src/winston.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,8 +211,7 @@ describe("Winston logging tests", () => {

const logs = await logged;

const context = logs[0].context as Context;
const runtime = context.runtime as Context;
expect(runtime.file).toMatch("winston.test.ts");
const context = logs[0].context;
expect(context.runtime.file).toMatch("winston.test.ts");
});
});

0 comments on commit 20a6b79

Please sign in to comment.