日志记录
为你的 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.
使用项目的包管理器添加依赖:
¥Use your project’s package manager to add the dependency:
npm run tauri add log
yarn run tauri add log
pnpm tauri add log
deno task tauri add log
bun tauri add log
cargo tauri add log
-
Run the following command in the
src-tauri
folder to add the plugin to the project’s dependencies inCargo.toml
:cargo add tauri-plugin-log -
Modify
lib.rs
to initialize the plugin:src-tauri/src/lib.rs #[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");} -
Install the JavaScript Guest bindings using your preferred JavaScript package manager:
npm install @tauri-apps/plugin-logyarn add @tauri-apps/plugin-logpnpm add @tauri-apps/plugin-logdeno add npm:@tauri-apps/plugin-logbun add @tauri-apps/plugin-log
使用
¥Usage
-
首先,你需要向 Tauri 注册插件。
¥First, you need to register the plugin with 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");} -
之后,所有插件的 API 都可以通过 JavaScript 来宾绑定获得:
¥Afterwards, all the plugin’s APIs are available through the JavaScript guest bindings:
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
使用插件的 warn
、debug
、trace
、info
或 error
API 之一从 JavaScript 代码生成日志记录:
¥Use one of the plugin’s warn
, debug
, trace
, info
or error
APIs to produce a log record from JavaScript code:
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);
要在 Rust 端创建自己的日志,你可以使用 [log
crate]:
¥To create your own logs on the Rust side you can use the [log
crate]:
log::error!("something bad happened!");log::info!("Tauri is awesome!");
请注意,必须将 [log
crate] 添加到你的 Cargo.toml
文件中:
¥Note that the [log
crate] must be added to your Cargo.toml
file:
[dependencies]log = "0.4"
日志目标
¥Log targets
日志插件构建器具有 targets
函数,可让你配置所有应用日志的通用目标。
¥The log plugin builder has a targets
function that lets you configure common destination of all your application logs.
:::note 注意
默认情况下,插件会记录到 stdout 和应用日志目录中的文件中。要仅使用你自己的日志目标,请调用 clear_targets
:
¥By default the plugin logs to stdout and to a file in the application logs directory.
To only use your own log targets, call clear_targets
:
tauri_plugin_log::Builder::new().clear_targets().build()
:::
将日志打印到终端
¥Printing logs to the terminal
要将所有日志转发到终端,请启用 Stdout
或 Stderr
目标:
¥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.
记录到 webview 控制台
¥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
要将所有日志写入文件,你可以使用 LogDir
或 Folder
目标。
¥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 | {configDir}/{bundleIdentifier} | /home/alice/.config/com.tauri.dev |
macOS | {homeDir}/Library/Logs/{bundleIdentifier} | /Users/Alice/Library/Logs/com.tauri.dev |
Windows | {FOLDERID_LocalAppData}/{bundleIdentifier}/logs | C:\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()
在此示例中,调试和跟踪日志被丢弃,因为它们的级别低于信息。
¥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.
{ "$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
allow-log
Permission Table
Identifier | Description |
---|---|
|
Enables the log command without any pre-configured scope. |
|
Denies the log command without any pre-configured scope. |
Tauri 中文网 - 粤ICP备13048890号