跳转到内容
Tauri

日志记录

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

支持的平台

此插件需要 Rust 版本至少为 1.77.2

平台 级别 备注
windows
linux
macos
android
ios

设置

安装日志插件以开始使用。

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

npm run tauri add log

用法

  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 Guest 绑定使用

    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;

日志记录

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

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

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

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);

日志目标

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

将日志打印到终端

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

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

此目标默认启用。

将日志记录到 Webview 控制台

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

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

持久化日志

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

  • 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 目标时,所有日志都存储在推荐的日志目录中。下表描述了每个平台的日志位置

平台示例
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:

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

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 是应用程序名称。

配置日志文件行为

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

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

Tauri 可以在日志文件达到大小限制时自动轮换它,而不是丢弃之前的文件。此行为可以使用 rotation_strategy 配置

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

过滤

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

最大日志级别

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

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

在此示例中,debug 和 trace 日志被丢弃,因为它们的级别低于 info

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

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 文件中

[dependencies]
log = "0.4"

目标过滤器

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

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

格式化

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

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

日志日期

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

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

权限

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

有关更多信息,请参阅 能力概述使用插件权限的分步指南 以了解如何使用插件权限。

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"]
}

默认权限

允许日志命令

此默认权限集包括以下内容

  • allow-log

权限表

标识符 描述

log:allow-log

启用日志命令,无需任何预配置的作用域。

log:deny-log

拒绝日志命令,无需任何预配置的作用域。


© 2025 Tauri 贡献者。CC-BY / MIT