Skip to content

Commit

Permalink
Add option for log-socket (#25)
Browse files Browse the repository at this point in the history
This is to enable logging to the output pane in VSCode. Other users can
also use this feature if they want to log out to a specific server.
  • Loading branch information
esarver authored Jul 26, 2024
1 parent 08e15ac commit 7860024
Show file tree
Hide file tree
Showing 5 changed files with 226 additions and 27 deletions.
5 changes: 4 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,11 @@ Check [Keep a Changelog](http://keepachangelog.com/) for recommendations on how

## [0.17.0]

### Added
- Added logging infrastructure over socket, in files, and to stderr in `kic` and `kic-discover`.

### Fixed
- Fixed an indexing issue for uploading modules (TSP-761) *Open Source Contribution: c3charvat, amcooper181*
- Fixed an indexing issue for upgrading module firmware (TSP-761) *Open Source Contribution: c3charvat, amcooper181*

## [0.16.2]

Expand Down
19 changes: 16 additions & 3 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ serde_json = "1.0.114"
thiserror = "1.0.58"
tmc = { git = "https://github.com/esarver/rusb-usbtmc" }
tracing = { version = "0.1.40", features = ["async-await"] }
tracing-subscriber = "0.3.18"
tracing-subscriber = { version = "0.3.18", features = ["json"] }
tsp-toolkit-kic-lib = { git = "https://github.com/tektronix/tsp-toolkit-kic-lib.git", tag = "v0.16.1" }

[workspace.lints.rust]
Expand Down
120 changes: 106 additions & 14 deletions kic-discover/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,14 @@ use tracing::{error, info, instrument, level_filters::LevelFilter, trace, warn};
use tracing_subscriber::{layer::SubscriberExt, Layer, Registry};
use tsp_toolkit_kic_lib::instrument::info::InstrumentInfo;

use std::collections::HashSet;
use std::fs::OpenOptions;
use std::str;
use std::time::Duration;
use std::{
collections::HashSet,
net::{SocketAddr, TcpStream},
sync::Mutex,
};

use clap::{command, Args, Command, FromArgMatches, Parser, Subcommand};

Expand All @@ -21,14 +25,18 @@ use kic_discover::DISC_INSTRUMENTS;
#[derive(Debug, Parser)]
#[command(author, version, about, long_about = None)]
struct Cli {
/// Enable logging to stderr. When used with `--log-file`, logs will be written to both stderr and the given log file.
/// Enable logging to stderr. Can be used in conjunction with `--log-file` and `--verbose`.
#[arg(global = true, short = 'v', long = "verbose")]
verbose: bool,

/// Log to the given log file path. If not set, logging will not occur unless `--verbose` is set.
/// Log to the given log file path. Can be used in conjunction with `--log-socket` and `--verbose`.
#[arg(name = "log-file", global = true, short = 'l', long = "log-file")]
log_file: Option<PathBuf>,

/// Log to the given socket (in IPv4 or IPv6 format with port number). Can be used in conjunction with `--log-file` and `--verbose`.
#[arg(name = "log-socket", global = true, short = 's', long = "log-socket")]
log_socket: Option<SocketAddr>,

#[command(subcommand)]
conn: SubCli,
}
Expand All @@ -45,14 +53,18 @@ enum SubCli {

#[derive(Debug, Args, Clone, PartialEq)]
pub(crate) struct DiscoverCmd {
/// Enable logging to stderr. When used with `--log-file`, logs will be written to both stderr and the given log file.
/// Enable logging to stderr. Can be used in conjunction with `--log-file` and `--verbose`.
#[arg(from_global)]
verbose: bool,

/// Log to the given log file path. If not set, logging will not occur unless `--verbose` is set.
/// Log to the given log file path. Can be used in conjunction with `--log-socket` and `--verbose`.
#[clap(name = "log-file", from_global)]
log_file: Option<PathBuf>,

/// Log to the given socket (in IPv4 or IPv6 format with port number). Can be used in conjunction with `--log-file` and `--verbose`.
#[clap(name = "log-socket", from_global)]
log_socket: Option<SocketAddr>,

/// Print JSON-encoded instrument information.
#[clap(long)]
json: bool,
Expand All @@ -68,9 +80,40 @@ pub(crate) struct DiscoverCmd {
exit: bool,
}

fn start_logger(verbose: &bool, log_file: &Option<PathBuf>) -> anyhow::Result<()> {
match (verbose, log_file) {
(true, Some(l)) => {
fn start_logger(
verbose: &bool,
log_file: &Option<PathBuf>,
log_socket: &Option<SocketAddr>,
) -> anyhow::Result<()> {
match (verbose, log_file, log_socket) {
(true, Some(l), Some(s)) => {
let err = tracing_subscriber::fmt::layer()
.with_ansi(true)
.with_writer(std::io::stderr)
.with_filter(LevelFilter::INFO);

let log = OpenOptions::new().append(true).create(true).open(l)?;

let log = tracing_subscriber::fmt::layer()
.with_writer(log)
.fmt_fields(tracing_subscriber::fmt::format::DefaultFields::new())
.with_ansi(false);

let sock = TcpStream::connect(s)?;
let sock = tracing_subscriber::fmt::layer()
.with_writer(Mutex::new(sock))
.fmt_fields(tracing_subscriber::fmt::format::DefaultFields::new())
.json();

let logger = Registry::default()
.with(LevelFilter::TRACE)
.with(err)
.with(log)
.with(sock);

tracing::subscriber::set_global_default(logger)?;
}
(true, Some(l), None) => {
let err = tracing_subscriber::fmt::layer()
.with_ansi(true)
.with_writer(std::io::stderr)
Expand All @@ -90,7 +133,27 @@ fn start_logger(verbose: &bool, log_file: &Option<PathBuf>) -> anyhow::Result<()

tracing::subscriber::set_global_default(logger)?;
}
(false, Some(l)) => {
(false, Some(l), Some(s)) => {
let log = OpenOptions::new().append(true).create(true).open(l)?;

let log = tracing_subscriber::fmt::layer()
.with_writer(log)
.with_ansi(false);

let sock = TcpStream::connect(s)?;
let sock = tracing_subscriber::fmt::layer()
.with_writer(Mutex::new(sock))
.fmt_fields(tracing_subscriber::fmt::format::DefaultFields::new())
.json();

let logger = Registry::default()
.with(LevelFilter::TRACE)
.with(log)
.with(sock);

tracing::subscriber::set_global_default(logger)?;
}
(false, Some(l), None) => {
let log = OpenOptions::new().append(true).create(true).open(l)?;

let log = tracing_subscriber::fmt::layer()
Expand All @@ -101,7 +164,25 @@ fn start_logger(verbose: &bool, log_file: &Option<PathBuf>) -> anyhow::Result<()

tracing::subscriber::set_global_default(logger)?;
}
(true, None) => {
(true, None, Some(s)) => {
let err = tracing_subscriber::fmt::layer()
.with_ansi(true)
.with_writer(std::io::stderr);

let sock = TcpStream::connect(s)?;
let sock = tracing_subscriber::fmt::layer()
.with_writer(Mutex::new(sock))
.fmt_fields(tracing_subscriber::fmt::format::DefaultFields::new())
.json();

let logger = Registry::default()
.with(LevelFilter::TRACE)
.with(err)
.with(sock);

tracing::subscriber::set_global_default(logger)?;
}
(true, None, None) => {
let err = tracing_subscriber::fmt::layer()
.with_ansi(true)
.with_writer(std::io::stderr);
Expand All @@ -110,7 +191,18 @@ fn start_logger(verbose: &bool, log_file: &Option<PathBuf>) -> anyhow::Result<()

tracing::subscriber::set_global_default(logger)?;
}
(false, None) => {}
(false, None, Some(s)) => {
let sock = TcpStream::connect(s)?;
let sock = tracing_subscriber::fmt::layer()
.with_writer(Mutex::new(sock))
.fmt_fields(tracing_subscriber::fmt::format::DefaultFields::new())
.json();

let logger = Registry::default().with(LevelFilter::TRACE).with(sock);

tracing::subscriber::set_global_default(logger)?;
}
(false, None, None) => {}
}

info!("Application started");
Expand Down Expand Up @@ -152,7 +244,7 @@ async fn main() -> anyhow::Result<()> {

match sub {
SubCli::Lan(args) => {
start_logger(&args.verbose, &args.log_file)?;
start_logger(&args.verbose, &args.log_file, &args.log_socket)?;
info!("Discovering LAN instruments");
#[allow(clippy::mutable_key_type)]
let lan_instruments = match discover_lan(args).await {
Expand All @@ -171,7 +263,7 @@ async fn main() -> anyhow::Result<()> {
}
}
SubCli::Usb(args) => {
start_logger(&args.verbose, &args.log_file)?;
start_logger(&args.verbose, &args.log_file, &args.log_socket)?;
info!("Discovering USB instruments");
#[allow(clippy::mutable_key_type)]
let usb_instruments = match discover_usb().await {
Expand All @@ -189,7 +281,7 @@ async fn main() -> anyhow::Result<()> {
}
}
SubCli::All(args) => {
start_logger(&args.verbose, &args.log_file)?;
start_logger(&args.verbose, &args.log_file, &args.log_socket)?;
info!("Discovering USB instruments");
#[allow(clippy::mutable_key_type)]
let usb_instruments = match discover_usb().await {
Expand Down
Loading

0 comments on commit 7860024

Please sign in to comment.