-
-
Notifications
You must be signed in to change notification settings - Fork 38
ref(logs): Intercept Native SDK logs #1249
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
lucas-zimerman
wants to merge
15
commits into
main
Choose a base branch
from
lz/intercept-js-errors
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
fe4a21f
feat: add onNativeLog callback to intercept and forward native SDK lo…
lucas-zimerman daa6dff
fix(NativeLogListener): remove unnecessary type assertion on addListener
lucas-zimerman 7e72b97
fix(android): remove jetbrains annotations from CapSentryLogger
lucas-zimerman ffa7a37
fix(android): use emitter interface to avoid protected access on noti…
lucas-zimerman 53a676f
plugin order
lucas-zimerman 75f7180
validated changes on ios
lucas-zimerman 9efaf0b
added tests
lucas-zimerman 23a1725
Merge branch 'lz/intercept-js-errors' of https://github.com/getsentry…
lucas-zimerman 4a12586
Merge branch 'main' into lz/intercept-js-errors
lucas-zimerman ef826eb
changelog
lucas-zimerman 713f6d4
merge main
lucas-zimerman 1562275
Merge branch 'lz/intercept-js-errors' of https://github.com/getsentry…
lucas-zimerman 99baf27
fix(ios): mark NativeLogsForwarder as final and @unchecked Sendable t…
lucas-zimerman cb40606
chore: remove Package.resolved and add to .gitignore
lucas-zimerman 19cae50
chore: anchor Package.resolved gitignore rule to repo root
lucas-zimerman File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -26,6 +26,7 @@ example/*/.env | |
| Pods | ||
| Build | ||
| xcuserdata | ||
| /Package.resolved | ||
|
|
||
| # macOS files | ||
| .DS_Store | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
80 changes: 80 additions & 0 deletions
80
android/src/main/java/io/sentry/capacitor/CapSentryLogger.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| package io.sentry.capacitor; | ||
|
|
||
| import com.getcapacitor.JSObject; | ||
| import io.sentry.ILogger; | ||
| import io.sentry.SentryLevel; | ||
| import io.sentry.android.core.AndroidLogger; | ||
|
|
||
| /** | ||
| * Custom ILogger implementation that wraps AndroidLogger and forwards log messages to JS. | ||
| * This allows native SDK logs to appear in the browser console when debug mode is enabled. | ||
| */ | ||
| public class CapSentryLogger implements ILogger { | ||
| private static final String TAG = "CapacitorSentry"; | ||
|
|
||
| public interface NativeLogEmitter { | ||
| void emit(JSObject data); | ||
| } | ||
|
|
||
| private final AndroidLogger androidLogger; | ||
| private volatile NativeLogEmitter emitter; | ||
|
|
||
| public CapSentryLogger() { | ||
| this.androidLogger = new AndroidLogger(TAG); | ||
| } | ||
|
|
||
| public void setEmitter(NativeLogEmitter emitter) { | ||
| this.emitter = emitter; | ||
| } | ||
|
|
||
| @Override | ||
| public void log(SentryLevel level, String message, Object... args) { | ||
| androidLogger.log(level, message, args); | ||
|
|
||
| String formattedMessage = | ||
| (args == null || args.length == 0) ? message : String.format(message, args); | ||
| forwardToJS(level, formattedMessage); | ||
| } | ||
|
|
||
| @Override | ||
| public void log(SentryLevel level, String message, Throwable throwable) { | ||
| androidLogger.log(level, message, throwable); | ||
|
|
||
| String fullMessage = throwable != null ? message + ": " + throwable.getMessage() : message; | ||
| forwardToJS(level, fullMessage); | ||
| } | ||
|
|
||
| @Override | ||
| public void log(SentryLevel level, Throwable throwable, String message, Object... args) { | ||
| androidLogger.log(level, throwable, message, args); | ||
|
|
||
| String formattedMessage = | ||
| (args == null || args.length == 0) ? message : String.format(message, args); | ||
| if (throwable != null) { | ||
| formattedMessage += ": " + throwable.getMessage(); | ||
| } | ||
| forwardToJS(level, formattedMessage); | ||
| } | ||
|
|
||
| @Override | ||
| public boolean isEnabled(SentryLevel level) { | ||
| return androidLogger.isEnabled(level); | ||
| } | ||
|
|
||
| private void forwardToJS(SentryLevel level, String message) { | ||
| NativeLogEmitter currentEmitter = emitter; | ||
| if (currentEmitter == null) { | ||
| return; | ||
| } | ||
|
|
||
| try { | ||
| JSObject data = new JSObject(); | ||
| data.put("level", level.name().toLowerCase()); | ||
| data.put("component", "Sentry"); | ||
| data.put("message", message); | ||
| currentEmitter.emit(data); | ||
| } catch (Exception e) { | ||
| androidLogger.log(SentryLevel.DEBUG, "Failed to forward log to JS: " + e.getMessage()); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
23 changes: 0 additions & 23 deletions
23
example/ionic-angular-v7/ios/App/App.xcworkspace/xcshareddata/swiftpm/Package.resolved
This file was deleted.
Oops, something went wrong.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
93 changes: 93 additions & 0 deletions
93
ios/Sources/SentryCapacitorPlugin/SentryCapacitorNativeLogsForwarder.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| import Foundation | ||
| import Capacitor | ||
| @_spi(Private) @preconcurrency import Sentry | ||
|
|
||
| private let nativeLogEventName = "SentryNativeLog" | ||
|
|
||
| /** | ||
| * Singleton class that forwards native Sentry SDK logs to JavaScript via Capacitor events. | ||
| * This allows developers to see native SDK logs in the browser console when debug mode is enabled. | ||
| * | ||
| * Note: iOS log forwarding requires sentry-cocoa to expose `SentrySDKLog.setOutput`. | ||
| * See: https://github.com/getsentry/sentry-cocoa/pull/7444 | ||
| */ | ||
| final class SentryCapacitorNativeLogsForwarder: @unchecked Sendable { | ||
| static let shared = SentryCapacitorNativeLogsForwarder() | ||
|
|
||
| private weak var plugin: CAPPlugin? | ||
|
|
||
| private init() {} | ||
|
|
||
| func configure(plugin: CAPPlugin) { | ||
| self.plugin = plugin | ||
|
|
||
| SentrySDKLog.setOutput { [weak self] message in | ||
| // Always print to console (default behavior) | ||
| NSLog("%@", message) | ||
|
|
||
| guard let self = self else { return } | ||
| self.forwardLogMessage(message) | ||
| } | ||
| } | ||
|
|
||
| func stopForwarding() { | ||
| self.plugin = nil | ||
| SentrySDKLog.setOutput { message in NSLog("%@", message) } | ||
| } | ||
|
|
||
| private func forwardLogMessage(_ message: String) { | ||
| guard let plugin = self.plugin else { return } | ||
| guard message.hasPrefix("[Sentry]") else { return } | ||
|
|
||
| let level = extractLevel(from: message) | ||
| let component = extractComponent(from: message) | ||
| let cleanMessage = extractCleanMessage(from: message) | ||
|
|
||
| let body: [String: Any] = [ | ||
| "level": level, | ||
| "component": component, | ||
| "message": cleanMessage, | ||
| ] | ||
|
|
||
| DispatchQueue.main.async { [weak plugin] in | ||
| plugin?.notifyListeners(nativeLogEventName, data: body) | ||
| } | ||
| } | ||
|
|
||
| private func extractLevel(from message: String) -> String { | ||
| let pattern = "\\[(debug|info|warning|error|fatal)\\]" | ||
| guard let regex = try? NSRegularExpression(pattern: pattern, options: .caseInsensitive), | ||
| let match = regex.firstMatch(in: message, range: NSRange(message.startIndex..., in: message)), | ||
| match.numberOfRanges > 1, | ||
| let range = Range(match.range(at: 1), in: message) | ||
| else { | ||
| return "info" | ||
| } | ||
| return String(message[range]).lowercased() | ||
| } | ||
|
|
||
| private func extractComponent(from message: String) -> String { | ||
| let pattern = "\\[([A-Za-z]+):\\d+\\]" | ||
| guard let regex = try? NSRegularExpression(pattern: pattern), | ||
| let match = regex.firstMatch(in: message, range: NSRange(message.startIndex..., in: message)), | ||
| match.numberOfRanges > 1, | ||
| let range = Range(match.range(at: 1), in: message) | ||
| else { | ||
| return "Sentry" | ||
| } | ||
| return String(message[range]) | ||
| } | ||
|
|
||
| private func extractCleanMessage(from message: String) -> String { | ||
| let pattern = "^\\[Sentry\\]\\s*\\[[^\\]]+\\]\\s*\\[[^\\]]+\\]\\s*(?:\\[[^\\]]+\\]\\s*)?" | ||
| guard let regex = try? NSRegularExpression(pattern: pattern) else { | ||
| return message | ||
| } | ||
| let result = regex.stringByReplacingMatches( | ||
| in: message, | ||
| range: NSRange(message.startIndex..., in: message), | ||
| withTemplate: "" | ||
| ) | ||
| return result.trimmingCharacters(in: .whitespaces) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| import type { PluginListenerHandle } from '@capacitor/core'; | ||
| import { Capacitor } from '@capacitor/core'; | ||
| import { debug } from '@sentry/core'; | ||
| import type { NativeLogEntry } from './options'; | ||
| import { SentryCapacitor } from './plugin'; | ||
|
|
||
| const NATIVE_LOG_EVENT_NAME = 'SentryNativeLog'; | ||
|
|
||
| let _removeListener: (() => void) | undefined; | ||
|
|
||
| async function registerNativeListener( | ||
| callback: (log: NativeLogEntry) => void, | ||
| setHandle: (listener: PluginListenerHandle) => void, | ||
| isRemoved: () => boolean, | ||
| ): Promise<void> { | ||
| const listenerHandle = await SentryCapacitor.addListener(NATIVE_LOG_EVENT_NAME, callback); | ||
| if (isRemoved()) { | ||
| await listenerHandle.remove(); | ||
| } else { | ||
| setHandle(listenerHandle); | ||
| debug.log('Native log listener set up successfully.'); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Sets up the native log listener that forwards logs from the native SDK to JS. | ||
| * This only works when `debug: true` is set in Sentry options. | ||
| * | ||
| * @param callback - The callback to invoke when a native log is received. | ||
| */ | ||
| export function setupNativeLogListener(callback: (log: NativeLogEntry) => void): void { | ||
| if (_removeListener) { | ||
| return; | ||
| } | ||
|
|
||
| const platform = Capacitor.getPlatform(); | ||
| if (platform !== 'ios' && platform !== 'android') { | ||
| debug.log('Native log listener is only supported on iOS and Android.'); | ||
| return; | ||
| } | ||
|
|
||
| let listenerHandle: PluginListenerHandle | undefined; | ||
| let removed = false; | ||
|
|
||
| _removeListener = () => { | ||
| removed = true; | ||
| _removeListener = undefined; | ||
| void listenerHandle?.remove(); | ||
| }; | ||
|
|
||
| registerNativeListener( | ||
| callback, | ||
| listener => { listenerHandle = listener; }, | ||
| () => removed, | ||
| ).catch((error: unknown) => { | ||
| debug.warn('Failed to set up native log listener:', error); | ||
| _removeListener = undefined; | ||
| }); | ||
| } | ||
|
|
||
| /** | ||
| * Removes the native log listener previously set up by `setupNativeLogListener`. | ||
| */ | ||
| export function stopNativeLogListener(): void { | ||
| _removeListener?.(); | ||
| } | ||
|
|
||
| /** | ||
| * Default handler for native logs that uses Sentry's debug logger. | ||
| * This avoids interference with captureConsoleIntegration which would | ||
| * otherwise capture these logs as breadcrumbs or events. | ||
| */ | ||
| export function defaultNativeLogHandler(log: NativeLogEntry): void { | ||
| const message = `[Native] [${log.component}] ${log.message}`; | ||
|
|
||
| switch (log.level.toLowerCase()) { | ||
| case 'fatal': | ||
| case 'error': | ||
| debug.error(message); | ||
| break; | ||
| case 'warning': | ||
| debug.warn(message); | ||
| break; | ||
| case 'info': | ||
| case 'debug': | ||
| default: | ||
| debug.log(message); | ||
| break; | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Unprotected
String.formatcan throw uncaught exceptionMedium Severity
The
String.format(message, args)calls in thelogmethods are not wrapped in try-catch. The underlyingAndroidLogger.log()internally catchesIllegalFormatExceptionfrom malformed format strings (this was a known crash, sentry-java#1985), but the subsequentString.formatcall inCapSentryLoggerlacks this same protection. If format specifiers inmessagedon't matchargs, anIllegalFormatExceptionwill propagate uncaught into the SDK internals.Additional Locations (1)
android/src/main/java/io/sentry/capacitor/CapSentryLogger.java#L50-L52Reviewed by Cursor Bugbot for commit 19cae50. Configure here.