📑

Tauri v2でloggingをする方法

に公開

注意事項

Tauri v1とTauri v2で手順が違うので、v1を使用している方は

ブラウザバックしてください。

手順

Cargo.tomlに必要なプラグインを追加する。

[dependencies]
tauri-plugin-log = "2.8.0"
log = "0.4"
chrono = "0.4"

tauri-plugin-log
log
Tauri公式のロギングプラグイン

Logging(ログ記録) | Tauri

chrono
chrono - Rust
ファイル名にタイムスタンプを追加するために入れている。


ログファイルを出力する処理とログを書き込む処理を書く。

logging.rs
use chrono::Local;
use std::env;
use tauri_plugin_log::{Builder, Target, TargetKind};

pub fn init<R: tauri::Runtime>() -> tauri::plugin::TauriPlugin<R> {
    // 現在時刻から yyyy_mmdd_HHMM 形式の文字列を生成
    let now = Local::now();
    let file_name = format!("{}.log", now.format("%Y_%m%d_%H%M"));

    Builder::new()
        .targets([
            Target::new(TargetKind::Stdout),
            Target::new(TargetKind::Folder {
                path: {
                    // 実行ファイルのパス
                    let mut path = env::current_exe()
                        .expect("failed to get exe path")
                        .parent()
                        .expect("failed to get parent dir")
                        .to_path_buf();
                    path.push("logs");
                    path
                },
                // 生成した固定のファイル名を指定
                file_name: Some(file_name),
            }),
        ])
        .format(|out, message, record| {
            out.finish(format_args!(
                "{} [{}] {}",
                Local::now().format("%Y-%m-%d %H:%M:%S"), // 秒まで表示
                record.level().to_string().to_lowercase(), // [debug] 等
                message
            ))
        })
        .level(log::LevelFilter::Info)
        .build()
}

ログファイルの出力先

環境 current_exe() の場所
開発時 src-tauri/target/debug/
本番 (Mac) AppName.app/Contents/MacOS/
本番 (Win) インストール先のフォルダ内

current_exe in std::env - Rust


libs.rs内にあるTauriの呼び出し処理にloggingを追加する。

libs.rs
// logging.rsをインポート
mod logging;

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .plugin(
            tauri_plugin_log::Builder::new()
                .level(tauri_plugin_log::log::LevelFilter::Info)
                .build(),
        )
        .plugin(tauri_plugin_opener::init())
        // loggingを登録
        .plugin(logging::init())
        .invoke_handler(tauri::generate_handler![greet])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}


src-tauri/capabilities/default.json (または main.json) にlog関数を登録する。

これを行わないとフロントエンド側でセキュリティ上の理由で弾かれる。

default.json
{
  "$schema": "../gen/schemas/desktop-schema.json",
  "identifier": "default",
  "windows": ["main"],
  "permissions": [
    "core:default",
    // ↓追加
    "log:default"
  ]
}

モジュールをインストールする。
今回はnpmでインストールしたが、使用しているパッケージマネージャーが異なる場合は、
コマンドをそれに合わせて変更すること。

npm run tauri add log
npm add @tauri-apps/plugin-log

log
Logging(ログ記録) | Tauri

@tauri-apps/plugin-log
plugins-workspace/plugins/log at v2 · tauri-apps/plugins-workspace · GitHub


logger.tsにlogging.rsに定義したloggingを呼び出す処理を書く。

logger.ts
import { info, warn, error, debug, trace } from '@tauri-apps/plugin-log';

// ログレベルの型定義
type LogLevel = 'info' | 'warn' | 'error' | 'debug' | 'trace';

const logToBoth = (level: LogLevel, message: string) => {
  // 1. ブラウザのコンソールに出力
  // 表示例: [info] ユーザーがログインしました
  console.log(`[${level}] ${message}`);

  // 2. Rust経由でファイルに出力(awaitせず非同期で実行)
  switch (level) {
    case 'info': info(message).catch(console.error); break;
    case 'warn': warn(message).catch(console.error); break;
    case 'error': error(message).catch(console.error); break;
    case 'debug': debug(message).catch(console.error); break;
    case 'trace': trace(message).catch(console.error); break;
  }
};

export const logger = {
  info: (msg: string) => logToBoth('info', msg),
  warn: (msg: string) => logToBoth('warn', msg),
  error: (msg: string) => logToBoth('error', msg),
  debug: (msg: string) => logToBoth('debug', msg),
  trace: (msg: string) => logToBoth('trace', msg),
};


ログを出力したい箇所でloggerを呼び出す。

logger.info("info")
logger.debug("debug")
logger.warn("warn")
logger.error("error")

以上おわり!

Discussion