Skip to content
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

fix(log): inconsistent webview log target #2021

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changes/fix-inconsistent-webview-log-target.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'log-plugin': 'patch'
'log-js': 'patch'
---

Make webview log target more consistent that it always starts with `webview`
2 changes: 1 addition & 1 deletion plugins/log/api-iife.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

74 changes: 64 additions & 10 deletions plugins/log/guest-js/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,24 +44,78 @@ enum LogLevel {
Error
}

function getCallerLocation(stack?: string) {
if (!stack) {
return
}

if (stack.startsWith('Error')) {
// Assume it's Chromium V8
//
// Error
// at baz (filename.js:10:15)
// at bar (filename.js:6:3)
// at foo (filename.js:2:3)
// at filename.js:13:1

const lines = stack.split('\n')
// Find the third line (caller's caller of the current location)
const callerLine = lines[3].trim()

const regex =
/at\s+(?<functionName>.*?)\s+\((?<fileName>.*?):(?<lineNumber>\d+):(?<columnNumber>\d+)\)/
const match = callerLine.match(regex)

if (match) {
const { functionName, fileName, lineNumber, columnNumber } =
match.groups as {
functionName: string
fileName: string
lineNumber: string
columnNumber: string
}
return `${functionName}@${fileName}:${lineNumber}:${columnNumber}`
} else {
// Handle cases where the regex does not match (e.g., last line without function name)
const regexNoFunction =
/at\s+(?<fileName>.*?):(?<lineNumber>\d+):(?<columnNumber>\d+)/
const matchNoFunction = callerLine.match(regexNoFunction)
if (matchNoFunction) {
const { fileName, lineNumber, columnNumber } =
matchNoFunction.groups as {
fileName: string
lineNumber: string
columnNumber: string
}
return `<anonymous>@${fileName}:${lineNumber}:${columnNumber}`
}
}
} else {
// Assume it's Webkit JavaScriptCore, example:
//
// baz@filename.js:10:24
// bar@filename.js:6:6
// foo@filename.js:2:6
// global code@filename.js:13:4

const traces = stack.split('\n').map((line) => line.split('@'))
const filtered = traces.filter(([name, location]) => {
return name.length > 0 && location !== '[native code]'
})
// Find the third line (caller's caller of the current location)
return filtered[2].filter((v) => v.length > 0).join('@')
}
}

async function log(
level: LogLevel,
message: string,
options?: LogOptions
): Promise<void> {
const traces = new Error().stack?.split('\n').map((line) => line.split('@'))

const filtered = traces?.filter(([name, location]) => {
return name.length > 0 && location !== '[native code]'
})
const location = getCallerLocation(new Error().stack)

const { file, line, keyValues } = options ?? {}

let location = filtered?.[0]?.filter((v) => v.length > 0).join('@')
if (location === 'Error') {
location = 'webview::unknown'
}

await invoke('plugin:log|log', {
level,
message,
Expand Down
24 changes: 9 additions & 15 deletions plugins/log/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ use tauri::{AppHandle, Emitter};
pub use fern;
use time::OffsetDateTime;

pub const WEBVIEW_TARGET: &str = "Webview";
pub const WEBVIEW_TARGET: &str = "webview";

#[cfg(target_os = "ios")]
mod ios {
Expand Down Expand Up @@ -230,22 +230,16 @@ fn log(
line: Option<u32>,
key_values: Option<HashMap<String, String>>,
) {
let location = location.unwrap_or("webview");

let level = log::Level::from(level);

let metadata = log::MetadataBuilder::new()
.level(level)
.target(WEBVIEW_TARGET)
.build();
let target = if let Some(location) = location {
format!("{WEBVIEW_TARGET}:{location}")
} else {
WEBVIEW_TARGET.to_string()
};

let mut builder = RecordBuilder::new();
builder
.level(level)
.metadata(metadata)
.target(location)
.file(file)
.line(line);
builder.level(level).target(&target).file(file).line(line);

let key_values = key_values.unwrap_or_default();
let mut kv = HashMap::new();
Expand Down Expand Up @@ -380,8 +374,8 @@ impl Builder {
/// .clear_targets()
/// .targets([
/// Target::new(TargetKind::Webview),
/// Target::new(TargetKind::LogDir { file_name: Some("webview".into()) }).filter(|metadata| metadata.target() == WEBVIEW_TARGET),
/// Target::new(TargetKind::LogDir { file_name: Some("rust".into()) }).filter(|metadata| metadata.target() != WEBVIEW_TARGET),
/// Target::new(TargetKind::LogDir { file_name: Some("webview".into()) }).filter(|metadata| metadata.target().starts_with(WEBVIEW_TARGET)),
/// Target::new(TargetKind::LogDir { file_name: Some("rust".into()) }).filter(|metadata| !metadata.target().starts_with(WEBVIEW_TARGET)),
/// ]);
/// ```
pub fn targets(mut self, targets: impl IntoIterator<Item = Target>) -> Self {
Expand Down
Loading