|
1 | 1 | import "cross-fetch/polyfill"; |
2 | 2 |
|
3 | | -import { ILogtailLog, ILogtailOptions } from "@logtail/types"; |
| 3 | +import { |
| 4 | + Context, |
| 5 | + ILogLevel, |
| 6 | + ILogtailLog, |
| 7 | + ILogtailOptions, |
| 8 | +} from "@logtail/types"; |
4 | 9 | import { Base } from "@logtail/core"; |
5 | 10 |
|
6 | 11 | // Awaiting: https://bugs.chromium.org/p/chromium/issues/detail?id=571722 |
@@ -41,7 +46,50 @@ export class Browser extends Base { |
41 | 46 | this.configureFlushOnPageLeave(); |
42 | 47 | } |
43 | 48 |
|
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 { |
45 | 93 | if (typeof document === "undefined") { |
46 | 94 | return; |
47 | 95 | } |
|
0 commit comments