Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions backend/crates/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,7 @@ pub(crate) mod utils;
/// in each row — belongs to whoever calls this.
#[cfg(feature = "logger")]
pub mod logger;

/// Background file output for tracing subscribers.
#[cfg(feature = "trace")]
pub mod trace;
82 changes: 82 additions & 0 deletions backend/crates/core/src/trace.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
//! File output for a tracing subscriber, enabled with the `trace` feature.
//!
//! The caller selects the path, creates its parent directory and configures the
//! subscriber's format and filters. Keep the returned guard until all producers
//! have stopped: dropping it requests a drain of the background writer.

use std::{fs::File, io, path::PathBuf};

use tracing_appender::non_blocking::{NonBlocking, NonBlockingBuilder, WorkerGuard};

/// File destination and behavior when the appender's bounded queue is full.
#[derive(Debug, Clone)]
pub struct TraceConfig {
/// Full file path. Its parent directory must already exist.
pub path: PathBuf,
/// Drop and count entries when full (`true`), or wait for capacity (`false`).
/// The count is available through the returned writer's `error_counter()`;
/// it counts dropped entries, not filesystem failures.
pub lossy: bool,
}

/// Create or truncate a trace file and start its background writer.
///
/// Use the writer with a JSON formatting layer for JSONL output. No subscriber
/// is installed here, and no rotation or extra queue is introduced. The guard
/// must outlive producers and be dropped during controlled application shutdown.
///
/// # Errors
///
/// Returns an I/O error if the destination cannot be opened. Background writes
/// and shutdown use `tracing-appender`'s error handling; this is not a fallible
/// flush or an acknowledgment that each entry reached disk.
pub fn open(config: TraceConfig) -> io::Result<(NonBlocking, WorkerGuard)> {
let file = File::create(config.path)?;
Ok(NonBlockingBuilder::default()
.lossy(config.lossy)
.finish(file))
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn json_events_are_persisted_when_the_guard_is_dropped()
-> Result<(), Box<dyn std::error::Error>> {
let directory = tempfile::tempdir()?;
let path = directory.path().join("trace.jsonl");
let (writer, guard) = open(TraceConfig {
path: path.clone(),
lossy: false,
})?;
let subscriber = tracing_subscriber::fmt()
.json()
.with_max_level(tracing::Level::INFO)
.with_writer(writer)
.finish();
tracing::subscriber::with_default(subscriber, || {
tracing::info!(session_id = 7, "session started");
tracing::warn!("warning, with \"quotes\"\nand a newline");
tracing::error!("file operation failed");
tracing::debug!("filtered out");
});
drop(guard);

let contents = std::fs::read_to_string(path)?;
let events = contents
.lines()
.map(serde_json::from_str::<serde_json::Value>)
.collect::<Result<Vec<_>, _>>()?;
assert_eq!(events.len(), 3);
assert_eq!(events[0]["level"], "INFO");
assert_eq!(events[0]["fields"]["session_id"], 7);
assert_eq!(events[1]["level"], "WARN");
assert_eq!(
events[1]["fields"]["message"],
"warning, with \"quotes\"\nand a newline"
);
assert_eq!(events[2]["level"], "ERROR");
Ok(())
}
}
62 changes: 62 additions & 0 deletions backend/crates/core/src/trace/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# Trace Module

[`trace.rs`](../trace.rs) opens a file and uses `tracing-appender` to write
diagnostic events on a background thread. Enable the `trace` feature to use it.
The caller configures the subscriber, JSON formatting and level filters.

## Configuration

`TraceConfig` has two fields:

| Field | Meaning |
| --- | --- |
| `path` | Destination file. Its parent directory must already exist. Opening creates or truncates the file. |
| `lossy` | `true`: drop entries when the queue is full; `false`: block the emitting thread until capacity is available. |

The module uses the appender's default queue capacity and does not rotate files.
`writer.error_counter().dropped_lines()` counts discarded entries, not disk errors.

## Example

The application depends on `software-core` with `features = ["trace"]`,
plus `tracing` and `tracing-subscriber` with its `json` feature.

```rust
use software_core::trace::{self, TraceConfig};

fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
std::fs::create_dir_all("logs")?;
let (writer, guard) = trace::open(TraceConfig {
path: "logs/trace.jsonl".into(),
lossy: true,
})?;

tracing_subscriber::fmt()
.json()
.with_max_level(tracing::Level::INFO)
.with_writer(writer)
.try_init()?;

tracing::info!("application started");
// Run the application and stop all producers before closing the trace.
tracing::info!("application stopped");
drop(guard);
Ok(())
}
```

This writes one JSON object per line, including `INFO`, `WARN` and `ERROR`.
`open()` itself does not install or replace a subscriber.

## Lifetime and errors

Keep the returned `WorkerGuard` alive until all modules have finished emitting
events. Dropping it requests the final drain; stopping a logging session does
not require closing a backend-wide trace. Abrupt exits that skip destructors
do not perform this shutdown.

`open()` returns file-opening errors. Background I/O and shutdown follow
`tracing-appender`'s behavior; the guard does not return a flush result.

In station, the intended destination is `logger/<backend-start>/others/trace.jsonl`.
Station chooses that path; core does not manage recording sessions.
Loading