Skip to content
Tauri 中文网

日志记录

为你的 Tauri 应用配置日志记录。

🌐 Configurable logging for your Tauri app.

🌐 Supported Platforms

This plugin requires a Rust version of at least 1.77.2

Platform Level Notes
windows
linux
macos
android
ios

🌐 Setup

安装日志插件即可开始使用。

🌐 Install the log plugin to get started.

使用项目的包管理器添加依赖:

npm run tauri add log

🌐 Usage

  1. 首先,你需要向 Tauri 注册插件。

    src-tauri/src/lib.rs
    use tauri_plugin_log::{Target, TargetKind};
    #[cfg_attr(mobile, tauri::mobile_entry_point)]
    pub fn run() {
    tauri::Builder::default()
    .plugin(tauri_plugin_log::Builder::new().build())
    .run(tauri::generate_context!())
    .expect("error while running tauri application");
    }
  2. 之后,所有插件的 API 都可以通过 JavaScript 来宾绑定获得:

    import {
    warn,
    debug,
    trace,
    info,
    error,
    attachConsole,
    attachLogger,
    } from '@tauri-apps/plugin-log';
    // when using `"withGlobalTauri": true`, you may use
    // const { warn, debug, trace, info, error, attachConsole, attachLogger } = window.__TAURI__.log;

🌐 Logging

使用插件的 warndebugtraceinfoerror API 从 JavaScript 代码生成日志记录:

import { warn, debug, trace, info, error } from '@tauri-apps/plugin-log';
trace('Trace');
info('Info');
error('Error');

要自动将所有 console 消息转发到日志插件,你可以重写它们:

🌐 To automatically forward all console messages to the log plugin you can rewrite them:

import { warn, debug, trace, info, error } from '@tauri-apps/plugin-log';
function forwardConsole(
fnName: 'log' | 'debug' | 'info' | 'warn' | 'error',
logger: (message: string) => Promise<void>
) {
const original = console[fnName];
console[fnName] = (message) => {
original(message);
logger(message);
};
}
forwardConsole('log', trace);
forwardConsole('debug', debug);
forwardConsole('info', info);
forwardConsole('warn', warn);
forwardConsole('error', error);

🌐 Log targets

日志插件构建器有一个 targets 函数,它允许你配置所有应用日志的常见目的地。

🌐 The log plugin builder has a targets function that lets you configure common destination of all your application logs.

🌐 Printing logs to the terminal

要将所有日志转发到终端,请启用 StdoutStderr 目标:

🌐 To forward all your logs to the terminal, enable the Stdout or Stderr targets:

tauri_plugin_log::Builder::new()
.target(tauri_plugin_log::Target::new(
tauri_plugin_log::TargetKind::Stdout,
))
.build()

此目标默认启用。

🌐 This target is enabled by default.

🌐 Logging to the webview console

要在 Webview 控制台中查看所有 Rust 日志,请启用 Webview 目标并在前端运行 attachConsole

🌐 To view all your Rust logs in the webview console, enable the Webview target and run attachConsole in your frontend:

tauri_plugin_log::Builder::new()
.target(tauri_plugin_log::Target::new(
tauri_plugin_log::TargetKind::Webview,
))
.build()
import { attachConsole } from '@tauri-apps/plugin-log';
const detach = await attachConsole();
// call detach() if you do not want to print logs to the console anymore

🌐 Persisting logs

要将所有日志写入文件,你可以使用 LogDirFolder 目标。

🌐 To write all logs to a file, you can use either the LogDir or the Folder targets.

  • LogDir:
tauri_plugin_log::Builder::new()
.target(tauri_plugin_log::Target::new(
tauri_plugin_log::TargetKind::LogDir {
file_name: Some("logs".to_string()),
},
))
.build()

使用 LogDir 目标时,所有日志都会存储在推荐的日志目录中。以下表格描述了各平台的日志位置:

🌐 When using the LogDir target, all logs are stored in the recommended log directory. The following table describes the location of the logs per platform:

平台示例
Linux$XDG_DATA_HOME/{bundleIdentifier}/logs$HOME/.local/share/{bundleIdentifier}/logs/home/alice/.local/share/com.tauri.dev/logs
macOS{homeDir}/Library/Logs/{bundleIdentifier}/Users/Alice/Library/Logs/com.tauri.dev
Windows{FOLDERID_LocalAppData}/{bundleIdentifier}/logsC:\Users\Alice\AppData\Local\com.tauri.dev\logs
  • Folder:

文件夹目标允许你将日志写入文件系统中的自定义位置。

🌐 The Folder target lets you write logs to a custom location in the filesystem.

tauri_plugin_log::Builder::new()
.target(tauri_plugin_log::Target::new(
tauri_plugin_log::TargetKind::Folder {
path: std::path::PathBuf::from("/path/to/logs"),
file_name: None,
},
))
.build()

默认的 file_name 是应用名称。

🌐 The default file_name is the application name.

🌐 Configuring log file behavior

默认情况下,当日志文件达到最大大小时,它会被丢弃。最大文件大小可以通过构建器的 max_file_size 函数进行配置:

🌐 By default the log file gets discarded when it reaches the maximum size. The maximum file size can be configured via the builder’s max_file_size function:

tauri_plugin_log::Builder::new()
.max_file_size(50_000 /* bytes */)
.build()

当日志文件达到大小限制时,Tauri 可以自动轮换日志文件,而不是丢弃之前的文件。这个行为可以通过 rotation_strategy 配置:

🌐 Tauri can automatically rotate your log file when it reaches the size limit instead of discarding the previous file. This behavior can be configured using rotation_strategy:

tauri_plugin_log::Builder::new()
.rotation_strategy(tauri_plugin_log::RotationStrategy::KeepAll)
.build()

🌐 Filtering

默认情况下,所有日志都会被处理。有一些机制可以减少日志量,并只过滤相关信息。

🌐 By default all logs are processed. There are some mechanisms to reduce the amount of logs and filter only relevant information.

🌐 Maximum log level

要设置最大日志级别,请使用 level 函数:

🌐 To set a maximum log level, use the level function:

tauri_plugin_log::Builder::new()
.level(log::LevelFilter::Info)
.build()

在这个例子中,调试和跟踪日志会被丢弃,因为它们的级别低于_info_。

🌐 In this example, debug and trace logs are discarded as they have a lower level than info.

还可以为各个模块定义单独的最大级别:

🌐 It is also possible to define separate maximum levels for individual modules:

tauri_plugin_log::Builder::new()
.level(log::LevelFilter::Info)
// verbose logs only for the commands module
.level_for("my_crate_name::commands", log::LevelFilter::Trace)
.build()

请注意,这些 API 使用了 log crate,必须将其添加到你的 Cargo.toml 文件中:

🌐 Note that these APIs use the log crate, which must be added to your Cargo.toml file:

[dependencies]
log = "0.4"

🌐 Target filter

filter 函数可以被定义为通过检查日志的元数据来丢弃不需要的日志:

🌐 A filter function can be defined to discard unwanted logs by checking their metadata:

tauri_plugin_log::Builder::new()
// exclude logs with target `"hyper"`
.filter(|metadata| metadata.target() != "hyper")
.build()

🌐 Formatting

日志插件将每条日志记录格式化为 DATE[TARGET][LEVEL] MESSAGE。 可以通过 format 提供自定义格式函数:

🌐 The log plugin formats each log record as DATE[TARGET][LEVEL] MESSAGE. A custom format function can be provided with format:

tauri_plugin_log::Builder::new()
.format(|out, message, record| {
out.finish(format_args!(
"[{} {}] {}",
record.level(),
record.target(),
message
))
})
.build()

🌐 Log dates

默认情况下,日志插件使用 UTC 时区来格式化日期,但你可以通过 timezone_strategy 将其配置为使用本地时区:

🌐 By default the log plugin uses the UTC timezone to format dates but you can configure it to use the local timezone with timezone_strategy:

tauri_plugin_log::Builder::new()
.timezone_strategy(tauri_plugin_log::TimezoneStrategy::UseLocal)
.build()

🌐 Permissions

默认情况下,所有插件命令都被阻止,无法访问。你必须在你的 capabilities 配置中定义权限列表。

🌐 By default, all plugin commands are blocked and cannot be accessed. You must define a list of permissions in your capabilities configuration.

有关更多信息,请参见功能概览,有关使用插件权限的分步指南,请参见分步指南

🌐 See the Capabilities Overview for more information and the step by step guide to use plugin permissions.

src-tauri/capabilities/default.json
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "main-capability",
"description": "Capability for the main window",
"windows": ["main"],
"permissions": ["log:default"]
}

Default Permission

Allows the log command

This default permission set includes the following:

  • allow-log

Permission Table

Identifier Description

log:allow-log

Enables the log command without any pre-configured scope.

log:deny-log

Denies the log command without any pre-configured scope.


Tauri 中文网 - 粤ICP备13048890号
Nodejs.cn 旗下网站