Skip to content

Commit

Permalink
fix(log): inconsistent webview log target (#2021)
Browse files Browse the repository at this point in the history
* Fix very inconsistent webview log target

* Add change file

* It's log-plugin not log

* Lower rust version requirement

* Use the third line instead of second
  • Loading branch information
Legend-Master authored Nov 12, 2024
1 parent 52c093a commit 371a2f7
Show file tree
Hide file tree
Showing 4 changed files with 80 additions and 26 deletions.
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:
//
// [email protected]:10:24
// [email protected]:6:6
// [email protected]:2:6
// global [email protected]: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

0 comments on commit 371a2f7

Please sign in to comment.