rusttauri

Save one log file per day with Tauri


I'm using the Tauri framework. I just configured tauri_plugin_log and it is working very well. The log files are being saved in the correct folders with the right names.

How can I save one log file per day? Reading the Tauri docs, I have not found anything that can help me to achieve that.

My current logs setup is this:

use chrono::Utc;

use tauri_plugin_log::{ Builder, RotationStrategy, Target, TargetKind };

pub fn setup_system_logs() -> Builder {
    Builder::new()
        .clear_targets()
        .rotation_strategy(RotationStrategy::KeepAll)
        .targets([
            Target::new(
                TargetKind::Folder {
                    file_name: Some(
                        Utc::now().format("%Y-%M-%d").to_string()
                    ),
                    path: std::path::PathBuf::from(
                        format!("{}/system", std::env::current_dir()
                            .unwrap_or_default()
                            .display()
                            .to_string()
                        )
                    )
                },
            ).filter(|metadata| metadata.target() == "system"),
            Target::new(
                TargetKind::Folder {
                    file_name: Some(
                        Utc::now().format("%Y-%M-%d").to_string()
                    ),
                    path: std::path::PathBuf::from(
                        format!("{}/api_responses", std::env::current_dir()
                            .unwrap_or_default()
                            .display()
                            .to_string()
                        )
                    )
                },
            ).filter(|metadata| metadata.target() == "api_responses")
        ])
}

Solution

  • Expanding on my comment.

    The Tauri log plugin uses fern under the hood to do the actual logging, which it also re-exports. It also exposes the Dispatch TargetKind which you can use to construct abritrary log targets. fern in turn has the DateBased you can use to create a target that rotates daily, something like so:

    use tauri_log_plugin::{fern};
    
    Builder::new()
        .clear_targets()
        .rotation_strategy(RotationStrategy::KeepAll)
        .targets([Target::new(TargetKind::Dispatch(
            fern::Dispatch::new().chain(fern::DateBased::new("logs/", "%Y-%m-%d-my-program.log")),
        ))])
    

    This adds a single target that writes to a file in logs/ with the pattern 2025-05-14-my-program.log. fern will automatically create a new file if the resulting filename has changed, so once it's the next day fern will close the old file and open a new one logs/2025-05-15-my-program.log.

    Note: to use DateBased from fern you need to add features = ["date-based"] when you're declaring the dependency.