tauri-apps / plugins-workspace

All of the official Tauri plugins in one place!
https://tauri.app
Apache License 2.0
815 stars 224 forks source link

[log] Using Tauri Plugin Log with a Yew frontend #35

Open ClementGre opened 1 year ago

ClementGre commented 1 year ago

Is there a way to use this plugin with yew, sending logs from rust in the frontend ?

Otherwise, is it a good practice to send a message from the frontend to the backend, and then calling appropriate info!, warn! etc. functions like described in the documentation : https://tauri.app/fr/v1/guides/features/command. This is the only alternative I've considered.

JonasKruckenberg commented 1 year ago

Once tauri-bindgen is ready we will provide Rustwasm bindings to the log plugin too, but for the time being you gotta implement this functionality yourself. https://github.com/tauri-apps/tauri-bindgen/blob/main/examples/test/src/tauri_log.rs is an example of this (you just gotta switch out the actual sending logic for something using invoke)

ClementGre commented 1 year ago

Thank's, then I don't have to use .wit files and I can just use a command in the backend:

#[tauri::command]
fn send_log(message: str, type: u16) {
  // match type
  info!(message);
}

And from Yew, sending commands using invoke.

I achieved that with this code in the backend:

use log::{debug, error, info, trace, warn};
use serde::{Serialize, Deserialize};

#[repr(usize)]
#[derive(Debug, Hash, Serialize, Deserialize)]
pub enum Level {
    Error,
    Warn,
    Info,
    Debug,
    Trace,
}

#[tauri::command]
pub fn log_from_front(message: &str, level: Level) {
    match level {
        Level::Error => error!("{}", message),
        Level::Warn => warn!("{}", message),
        Level::Info => info!("{}", message),
        Level::Debug => debug!("{}", message),
        Level::Trace => trace!("{}", message),
    }
}

And this code in the frontend:

use serde::{Serialize, Deserialize};
use serde_wasm_bindgen::to_value;
use wasm_bindgen::{prelude::wasm_bindgen, JsValue};

#[repr(usize)]
#[derive(Debug, Hash, Serialize, Deserialize)]
pub enum Level {
    Error,
    Warn,
    Info,
    Debug,
    Trace,
}

#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen(js_namespace = ["window", "__TAURI__", "tauri"])]
    fn invoke(cmd: &str, args: JsValue) -> JsValue;
}

#[derive(Serialize, Deserialize)]
struct LoggingMessage<'a> {
    message: &'a str,
    level: Level
}

pub fn error(msg: String){
    invoke("log_from_front", to_value(&LoggingMessage{message: &*msg, level: Level::Error}).unwrap());
}