Skip to content

Commit

Permalink
fix: Logger instance
Browse files Browse the repository at this point in the history
  • Loading branch information
Dam998 committed Feb 23, 2024
1 parent 74a1b9f commit 04b8336
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 6 deletions.
6 changes: 4 additions & 2 deletions lib/LogFlake.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,12 @@ export class LogFlake {
}

public async sendException<E extends Error>(exception: E, options?: Pick<IBodyLog, "correlation">) {
const { stack, message, ...params } = exception

return this.post<IBodyLog>(Queue.LOGS, {
content: exception.stack ?? exception.message ?? "Unknown error",
content: stack ?? message ?? "Unknown error",
level: LogLevels.EXCEPTION,
params: exception,
params,
hostname: this.hostname,
...options,
})
Expand Down
2 changes: 1 addition & 1 deletion lib/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import "whatwg-fetch"

export * from "./LogFlake"
export { LogFlake } from "./LogFlake"
export * from "./init"
12 changes: 11 additions & 1 deletion lib/init.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,22 @@
import { LogFlake } from "./LogFlake"
import { IBodyLog } from "./types"

export let Logger: LogFlake | null = null
let Logger: LogFlake | null = null

interface IInitOptions {
hostname?: string
enableCompression?: boolean
}

export const getLogger = () => {
return Logger
}

export const sendLog = (content: string, options?: Omit<IBodyLog, "content">) => getLogger()?.sendLog(content, options)
export const sendException = (error: Error, options?: Pick<IBodyLog, "correlation">) => getLogger()?.sendException(error, options)
export const measurePerformance = (label: string) => getLogger()?.measurePerformance(label)
export const sendPerformance = (label: string, duration: number) => getLogger()?.sendPerformance(label, duration)

export function initialize(appId: string, server?: string, options?: IInitOptions) {
if (Logger !== null) {
throw new Error("LogFlake is already initialized, if you want to initialize a new instance, use the LogFlake class directly.")
Expand Down
4 changes: 2 additions & 2 deletions tests/init.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Logger, initialize } from "../lib/init"
import { getLogger, initialize } from "../lib/init"

describe("initialize", () => {
expect(process.env.APP_ID).toBeDefined()
Expand All @@ -15,6 +15,6 @@ describe("initialize", () => {
expect(logInstance?.appId).toBe(APP_ID)
// @ts-expect-error
expect(logInstance?.server).toBe(SERVER)
expect(Logger).toBe(logInstance)
expect(getLogger()).toBe(logInstance)
})
})

0 comments on commit 04b8336

Please sign in to comment.