tauri_plugin_tracing/
types.rs

1//! Configuration types for the tracing plugin.
2
3use std::path::PathBuf;
4
5/// Specifies a log output destination.
6///
7/// Use these variants to configure where logs should be written. Multiple
8/// targets can be combined using [`Builder::target()`](crate::Builder::target) or [`Builder::targets()`](crate::Builder::targets).
9///
10/// # Example
11///
12/// ```rust,no_run
13/// use tauri_plugin_tracing::{Builder, Target};
14///
15/// // Log to stdout and webview (default behavior)
16/// Builder::new()
17///     .targets([Target::Stdout, Target::Webview])
18///     .build::<tauri::Wry>();
19///
20/// // Log to file and webview only (no console)
21/// Builder::new()
22///     .targets([
23///         Target::LogDir { file_name: None },
24///         Target::Webview,
25///     ])
26///     .build::<tauri::Wry>();
27///
28/// // Log to stderr instead of stdout
29/// Builder::new()
30///     .clear_targets()
31///     .target(Target::Stderr)
32///     .target(Target::Webview)
33///     .build::<tauri::Wry>();
34/// ```
35#[derive(Debug, Clone)]
36pub enum Target {
37    /// Print logs to stdout.
38    Stdout,
39
40    /// Print logs to stderr.
41    Stderr,
42
43    /// Forward logs to the webview via the `tracing://log` event.
44    ///
45    /// This allows JavaScript code to receive logs using `attachLogger()`
46    /// or `attachConsole()`.
47    Webview,
48
49    /// Write logs to the platform-standard log directory.
50    ///
51    /// Platform log directories:
52    /// - **macOS**: `~/Library/Logs/{bundle_identifier}`
53    /// - **Linux**: `~/.local/share/{bundle_identifier}/logs`
54    /// - **Windows**: `%LOCALAPPDATA%/{bundle_identifier}/logs`
55    ///
56    /// The `file_name` parameter sets the log file prefix. Defaults to `"app"`
57    /// if `None`, producing files like `app.2024-01-15.log`.
58    LogDir {
59        /// The log file prefix. Defaults to `"app"` if `None`.
60        file_name: Option<String>,
61    },
62
63    /// Write logs to a custom directory.
64    ///
65    /// The `file_name` parameter sets the log file prefix. Defaults to `"app"`
66    /// if `None`, producing files like `app.2024-01-15.log`.
67    Folder {
68        /// The directory path to write log files to.
69        path: PathBuf,
70        /// The log file prefix. Defaults to `"app"` if `None`.
71        file_name: Option<String>,
72    },
73}
74
75/// Time-based rotation period for log files.
76///
77/// This controls how often new log files are created.
78///
79/// # Example
80///
81/// ```rust,no_run
82/// use tauri_plugin_tracing::{Builder, Rotation};
83///
84/// Builder::new()
85///     .with_file_logging()
86///     .with_rotation(Rotation::Daily)  // Create new file each day
87///     .build::<tauri::Wry>();
88/// ```
89#[derive(Debug, Clone, Copy, Default)]
90pub enum Rotation {
91    /// Rotate logs daily. Files are named `app.YYYY-MM-DD.log`.
92    #[default]
93    Daily,
94    /// Rotate logs hourly. Files are named `app.YYYY-MM-DD-HH.log`.
95    Hourly,
96    /// Rotate logs every minute. Files are named `app.YYYY-MM-DD-HH-MM.log`.
97    Minutely,
98    /// Never rotate. All logs go to `app.log`.
99    Never,
100}
101
102/// Retention policy for rotated log files.
103///
104/// This controls how many old log files are kept when the application starts.
105///
106/// # Example
107///
108/// ```rust,no_run
109/// use tauri_plugin_tracing::{Builder, RotationStrategy};
110///
111/// Builder::new()
112///     .with_file_logging()
113///     .with_rotation_strategy(RotationStrategy::KeepSome(7))  // Keep 7 most recent files
114///     .build::<tauri::Wry>();
115/// ```
116#[derive(Debug, Clone, Copy, Default)]
117pub enum RotationStrategy {
118    /// Keep all rotated log files.
119    #[default]
120    KeepAll,
121    /// Keep only the current log file, deleting all previous ones.
122    KeepOne,
123    /// Keep the N most recent log files.
124    KeepSome(u32),
125}
126
127/// Log output format style.
128///
129/// Controls the overall structure and verbosity of log output.
130///
131/// # Example
132///
133/// ```rust,no_run
134/// use tauri_plugin_tracing::{Builder, LogFormat};
135///
136/// Builder::new()
137///     .with_format(LogFormat::Compact)
138///     .build::<tauri::Wry>();
139/// ```
140#[derive(Debug, Clone, Copy, Default)]
141pub enum LogFormat {
142    /// The default format with all information on a single line.
143    ///
144    /// Output: `2024-01-15T10:30:00.000Z INFO my_app: message field=value`
145    #[default]
146    Full,
147
148    /// A compact format optimized for shorter line lengths.
149    ///
150    /// Fields from the current span context are appended to the event fields
151    /// rather than displayed in a separate section.
152    Compact,
153
154    /// A multi-line, human-readable format for development.
155    ///
156    /// Includes colorful formatting, indentation, and verbose span information.
157    /// Best suited for local development and debugging.
158    Pretty,
159}
160
161/// Configuration options for log output formatting.
162///
163/// This struct bundles all the formatting options that control what
164/// information is included in log output.
165#[derive(Debug, Clone, Copy)]
166pub struct FormatOptions {
167    /// The overall format style.
168    pub format: LogFormat,
169    /// Whether to show the source file path.
170    pub file: bool,
171    /// Whether to show the source line number.
172    pub line_number: bool,
173    /// Whether to show thread IDs.
174    pub thread_ids: bool,
175    /// Whether to show thread names.
176    pub thread_names: bool,
177    /// Whether to show the log target (module path).
178    pub target: bool,
179    /// Whether to show the log level.
180    pub level: bool,
181}
182
183impl Default for FormatOptions {
184    fn default() -> Self {
185        Self {
186            format: LogFormat::default(),
187            file: false,
188            line_number: false,
189            thread_ids: false,
190            thread_names: false,
191            target: true,
192            level: true,
193        }
194    }
195}
196
197/// Maximum file size for log rotation.
198///
199/// Provides convenient constructors for common size units.
200///
201/// # Example
202///
203/// ```rust,no_run
204/// use tauri_plugin_tracing::{Builder, MaxFileSize};
205///
206/// Builder::new()
207///     .with_file_logging()
208///     .with_max_file_size(MaxFileSize::mb(10))  // Rotate at 10 MB
209///     .build::<tauri::Wry>();
210/// ```
211#[derive(Debug, Clone, Copy)]
212pub struct MaxFileSize(pub(crate) u64);
213
214impl MaxFileSize {
215    /// Creates a max file size from raw bytes.
216    pub const fn bytes(bytes: u64) -> Self {
217        Self(bytes)
218    }
219
220    /// Creates a max file size in kilobytes (KB).
221    pub const fn kb(kb: u64) -> Self {
222        Self(kb * 1024)
223    }
224
225    /// Creates a max file size in megabytes (MB).
226    pub const fn mb(mb: u64) -> Self {
227        Self(mb * 1024 * 1024)
228    }
229
230    /// Creates a max file size in gigabytes (GB).
231    pub const fn gb(gb: u64) -> Self {
232        Self(gb * 1024 * 1024 * 1024)
233    }
234
235    /// Returns the size in bytes.
236    pub const fn as_bytes(&self) -> u64 {
237        self.0
238    }
239}
240
241impl From<u64> for MaxFileSize {
242    fn from(bytes: u64) -> Self {
243        Self(bytes)
244    }
245}
246
247/// Timezone strategy for log timestamps.
248///
249/// Controls whether log timestamps are displayed in UTC or local time.
250///
251/// # Example
252///
253/// ```rust,no_run
254/// use tauri_plugin_tracing::{Builder, TimezoneStrategy};
255///
256/// Builder::new()
257///     .with_timezone_strategy(TimezoneStrategy::Local)
258///     .build::<tauri::Wry>();
259/// ```
260#[derive(Debug, Clone, Copy, Default)]
261pub enum TimezoneStrategy {
262    /// Use UTC timestamps (e.g., `2024-01-15T14:30:00.000000Z`).
263    ///
264    /// This is the default and most reliable option.
265    #[default]
266    Utc,
267
268    /// Use local timestamps with the system's timezone offset.
269    ///
270    /// The offset is captured when the logger is initialized. If the offset
271    /// cannot be determined (e.g., on some Unix systems with multiple threads),
272    /// falls back to UTC.
273    Local,
274}