Skip to content

Commit

Permalink
Merge pull request #12 from CramBL/better-logging-support
Browse files Browse the repository at this point in the history
Better logging support
  • Loading branch information
CramBL authored Oct 19, 2024
2 parents c61ef5f + 7af0ce2 commit 33a86f6
Show file tree
Hide file tree
Showing 10 changed files with 177 additions and 24 deletions.
10 changes: 9 additions & 1 deletion .cargo/config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,15 @@ linker = "arm-linux-gnueabihf-gcc"
rustflags = ["-C", "target-feature=+crt-static"]

[target.x86_64-unknown-linux-musl]
rustflags = ["-C", "target-feature=+crt-static"]
rustflags = [
"-C",
"target-feature=+crt-static",
"-C",
"link-self-contained=yes",
]

[target.x86_64-pc-windows-msvc]
rustflags = ["-C", "target-feature=+crt-static"]

[target.i686-pc-windows-msvc]
rustflags = ["-C", "target-feature=+crt-static"]
41 changes: 36 additions & 5 deletions .github/workflows/CI.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ name: CI
env:
RUSTFLAGS: -D warnings
RUSTDOCFLAGS: -D warnings
RUST_BACKTRACE: 1

jobs:
check:
Expand All @@ -36,7 +37,7 @@ jobs:
toolchain: stable
target: ${{ matrix.target }}
- uses: Swatinem/rust-cache@v2
- run: cargo check --target ${{ matrix.target }}
- run: cargo check --target ${{ matrix.target }} --all-targets

typos:
name: Spellcheck
Expand All @@ -52,15 +53,45 @@ jobs:
- uses: actions/checkout@v4
- run: cargo audit

test:
name: Test Suite
runs-on: ubuntu-latest
build-test:
name: Test Suite (native)
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ ubuntu-latest, macos-latest, windows-2022]
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- run: cargo build
- run: cargo test --workspace

cross-build-test:
name: Test Suite (Cross)
env:
CROSS_VERSION: v0.2.5
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
target: ["aarch64-unknown-linux-musl",
"arm-unknown-linux-musleabihf",
"armv7-unknown-linux-musleabihf"]
steps:
- uses: actions/checkout@v4
- name: Install Cargo Cross
run: |
curl -LO "https://github.com/cross-rs/cross/releases/download/${{ env.CROSS_VERSION }}/cross-x86_64-unknown-linux-musl.tar.gz"
tar xf cross-x86_64-unknown-linux-musl.tar.gz
- name: Build ${{ matrix.target }}
run: ./cross build --verbose --workspace --target ${{ matrix.target }}

- name: Test ${{ matrix.target }}
run: ./cross test --verbose --workspace --target ${{ matrix.target }}


format:
runs-on: ubuntu-latest
steps:
Expand All @@ -83,7 +114,7 @@ jobs:


tag-release:
needs: [check, audit, test, format, lint]
needs: [check, typos, audit, build-test, cross-build-test, format, lint]
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/master'
permissions:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ jobs:
# we specify bash to get pipefail; it guards against the `curl` command
# failing. otherwise `sh` won't catch that `curl` returned non-0
shell: bash
run: "curl --proto '=https' --tlsv1.2 -LsSf https://github.com/axodotdev/cargo-dist/releases/download/v0.23.0/cargo-dist-installer.sh | sh"
run: "curl --proto '=https' --tlsv1.2 -LsSf https://github.com/axodotdev/cargo-dist/releases/download/v0.22.1/cargo-dist-installer.sh | sh"
- name: Cache cargo-dist
uses: actions/upload-artifact@v4
with:
Expand Down
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

## Unreleased

- Allow logging to journald explicitly
- Allow setting logging destination to either `journald` (unix only), `stderr`, or `stdout`.

## [0.3.3]

### Changed
Expand Down
35 changes: 35 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ mime_guess = "2.0.5"
tokio = { version = "1.40", features = ["full"] }
tracing = "0.1"
tracing-subscriber = "0.3"
tracing-journald = "0.3.0"
local-ip-address = "0.6"
mdns-sd = "0.11"
chrono = "0.4"
Expand All @@ -38,6 +39,7 @@ tokio-stream = { version = "0.1.16", features = ["fs"] }
futures-util = "0.3"
percent-encoding = "2.3"
thiserror = "1.0"
strum = { version = "0.26", features = ["derive"] }

[dev-dependencies]
pretty_assertions = "1.4"
Expand Down
19 changes: 15 additions & 4 deletions dist-workspace.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,28 @@ members = ["cargo:."]
# Config for 'cargo dist'
[dist]
# The preferred cargo-dist version to use in CI (Cargo.toml SemVer syntax)
cargo-dist-version = "0.23.0"
cargo-dist-version = "0.22.1"
# CI backends to support
ci = "github"
# Target platforms to build apps for (Rust target-triple syntax)
targets = ["aarch64-apple-darwin", "aarch64-unknown-linux-musl", "aarch64-pc-windows-msvc", "arm-unknown-linux-musleabihf", "armv7-unknown-linux-musleabihf", "x86_64-apple-darwin", "x86_64-unknown-linux-gnu", "x86_64-unknown-linux-musl", "x86_64-pc-windows-msvc"]
targets = [
"aarch64-apple-darwin",
"aarch64-unknown-linux-musl",
"aarch64-pc-windows-msvc",
"arm-unknown-linux-musleabihf",
"armv7-unknown-linux-musleabihf",
"x86_64-apple-darwin",
"x86_64-unknown-linux-gnu",
"x86_64-unknown-linux-musl",
"x86_64-pc-windows-msvc",
"i686-pc-windows-msvc",
]
# The installers to generate for each app
installers = ["shell", "powershell", "npm", "msi"]
# The archive format to use for windows builds (defaults .zip)
windows-archive = ".zip"
windows-archive = ".tar.gz"
# The archive format to use for non-windows builds (defaults .tar.xz)
unix-archive = ".tar.xz"
unix-archive = ".tar.gz"
# Path that installers should place binaries in
install-path = "CARGO_HOME"
# Whether to install an updater program
Expand Down
2 changes: 1 addition & 1 deletion src/async_util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ pub async fn extract_file_details(entry: &tokio::fs::DirEntry) -> Result<FifeDir
Ok(true) => FileTypeCategory::DirectoryEmpty,
Ok(false) => FileTypeCategory::Directory,
Err(e) => {
tracing::error!("Error checking if directory '{file_name}' is empty: {}", e);
tracing::error!("Error checking if directory '{file_name}' is empty: {e}");
FileTypeCategory::Directory // Default to non-empty if there's an error
}
}
Expand Down
25 changes: 13 additions & 12 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,13 @@ use clap::{
},
Parser, ValueEnum,
};
use logging::Logging;
use std::path::{Path, PathBuf};
use tracing::Level;

pub const BIN_NAME: &str = "qft";
mod logging;

pub const BIN_NAME: &str = "fife";

#[derive(Parser, Debug)]
#[command(name = "Fidelity Fetch", version, styles = cli_styles())]
Expand All @@ -22,15 +25,19 @@ pub struct Config {
#[arg(short, long, default_value_t = 0)]
port: u16,

/// Verbosity of logging output (trace, debug, info, warn, error)
#[arg(short, long, default_value = "info")]
/// Verbosity of logging output (Not applicable when log=journald)
#[arg(short, long, default_value_t = LogLevel::Info)]
verbosity: LogLevel,

/// Optional service to register which can be used as the hostname to access served content.
/// e.g. `foo` will be available at `http://foo.local:<port>`
#[arg(short, long)]
mdns: Option<String>,

/// Where should logs be forwarded to
#[arg(short, long, default_value_t = Logging::Stderr)]
log: Logging,

/// Generate completion scripts for the specified shell.
/// Note: The completion script is printed to stdout
#[arg(
Expand Down Expand Up @@ -77,18 +84,12 @@ impl Config {
}

pub fn setup_logging(&self) {
let subscriber = tracing_subscriber::FmtSubscriber::builder()
.with_writer(std::io::stderr)
.with_max_level(self.verbosity())
.with_file(false)
.compact()
.finish();
tracing::subscriber::set_global_default(subscriber)
.expect("setting default subscriber failed");
logging::setup_logging(self.log, self.verbosity());
}
}

#[derive(Debug, ValueEnum, Clone, Copy)]
#[derive(Debug, ValueEnum, strum::Display, Clone, Copy)]
#[strum(serialize_all = "lowercase")]
enum LogLevel {
Trace,
Debug,
Expand Down
62 changes: 62 additions & 0 deletions src/config/logging.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
use std::io;

use clap::ValueEnum;
use tracing::Level;
use tracing_subscriber::util::SubscriberInitExt;

#[derive(Debug, strum::Display, Clone, Copy, ValueEnum)]
#[strum(serialize_all = "lowercase")]
pub enum Logging {
#[cfg(unix)]
/// Log to journald
Journald,
/// Log to stderr
Stderr,
/// Log to stdout
Stdout,
}

// Print extremely verbose output when running in debug mode
fn setup_debug_logging() {
tracing_subscriber::fmt()
.with_writer(io::stderr)
.with_max_level(Level::TRACE)
.with_target(true)
.with_file(true)
.with_line_number(true)
.pretty()
.finish()
.init();
}

pub(super) fn setup_logging(logging: Logging, loglevel: Level) {
if cfg!(debug_assertions) {
setup_debug_logging();
} else {
match logging {
#[cfg(unix)]
Logging::Journald => {
init_journald_logger().expect("Failed initializing journald logger");
}
Logging::Stderr | Logging::Stdout => {
let subscriber = tracing_subscriber::fmt()
.with_max_level(loglevel)
.with_target(false)
.with_file(false)
.with_line_number(false);
if matches!(logging, Logging::Stdout) {
subscriber.with_writer(io::stderr).finish().init();
} else {
subscriber.with_writer(io::stdout).finish().init();
};
}
}
}
}

#[cfg(unix)]
fn init_journald_logger() -> io::Result<()> {
let journald = tracing_journald::layer()?;
tracing_subscriber::layer::SubscriberExt::with(tracing_subscriber::registry(), journald).init();
Ok(())
}

0 comments on commit 33a86f6

Please sign in to comment.