Skip to content

Commit 3776601

Browse files
authored
L-841 [browser] Add context automatically (#99)
1 parent f2026bd commit 3776601

File tree

1 file changed

+50
-2
lines changed

1 file changed

+50
-2
lines changed

packages/browser/src/browser.ts

Lines changed: 50 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
import "cross-fetch/polyfill";
22

3-
import { ILogtailLog, ILogtailOptions } from "@logtail/types";
3+
import {
4+
Context,
5+
ILogLevel,
6+
ILogtailLog,
7+
ILogtailOptions,
8+
} from "@logtail/types";
49
import { Base } from "@logtail/core";
510

611
// Awaiting: https://bugs.chromium.org/p/chromium/issues/detail?id=571722
@@ -41,7 +46,50 @@ export class Browser extends Base {
4146
this.configureFlushOnPageLeave();
4247
}
4348

44-
private configureFlushOnPageLeave() {
49+
/**
50+
* Override `Base` log to add browser-specific context
51+
*
52+
* @param message: string - Log message
53+
* @param level (LogLevel) - Level to log at (debug|info|warn|error)
54+
* @param context: (Context) - Log context for passing structured data
55+
* @returns Promise<ILogtailLog> after syncing
56+
*/
57+
public async log<TContext extends Context>(
58+
message: string,
59+
level?: ILogLevel,
60+
context: TContext = {} as TContext,
61+
) {
62+
// Wrap context in an object, if it's not already
63+
if (typeof context !== "object") {
64+
const wrappedContext: unknown = { extra: context };
65+
context = wrappedContext as TContext;
66+
}
67+
if (context instanceof Error) {
68+
const wrappedContext: unknown = { error: context };
69+
context = wrappedContext as TContext;
70+
}
71+
72+
context = { ...this.getCurrentContext(), ...context };
73+
74+
return super.log(message, level, context);
75+
}
76+
77+
protected getCurrentContext(): Context {
78+
return {
79+
context: {
80+
url: window.location.href,
81+
user_locale: (navigator as any).userLanguage || navigator.language,
82+
user_agent: navigator.userAgent,
83+
device_pixel_ratio: window.devicePixelRatio,
84+
screen_width: window.screen.width,
85+
screen_height: window.screen.height,
86+
window_width: window.innerWidth,
87+
window_height: window.innerHeight,
88+
},
89+
};
90+
}
91+
92+
private configureFlushOnPageLeave(): void {
4593
if (typeof document === "undefined") {
4694
return;
4795
}

0 commit comments

Comments
 (0)