Rust 代码片断

来自百合仙子's Wiki
跳转到导航 跳转到搜索

时间日期

获取时间戳

fn timestamp() -> u64 {
  use std::time::{SystemTime, UNIX_EPOCH};
  let now = SystemTime::now();
  let elapsed = now.duration_since(UNIX_EPOCH).unwrap();
  elapsed.as_secs()
}

(用于取代旧的 time crate 中的 time::get_time().sec。)

格式化时间戳

fn format_timestamp(t: i64) -> Result<String> {
  let t = time::OffsetDateTime::from_unix_timestamp(t)?;
  let format = time::format_description::parse(
        "[year]-[month]-[day] [hour]:[minute]:[second] [offset_hour \
                 sign:mandatory]:[offset_minute]",
  )?;
  let offset = time::UtcOffset::local_offset_at(t)?;
  let s = t.to_offset(offset).format(&format)?;
  Ok(s)
}
cargo add time -F formatting,local-offset
cargo add eyre

日志

引入:

use tracing::{trace, debug, info, warn, error};
use tracing_subscriber::EnvFilter;
use std::io::IsTerminal;

初始化:

  // default RUST_LOG=warn
  let filter = EnvFilter::try_from_default_env()
    .unwrap_or_else(|_| EnvFilter::from("warn"));
  let isatty = std::io::stderr().is_terminal();
  let fmt = tracing_subscriber::fmt::fmt()
    .with_writer(std::io::stderr)
    .with_env_filter(filter)
    .with_ansi(isatty);
  if isatty {
    fmt
      .with_timer(tracing_subscriber::fmt::time::ChronoLocal::new(
          String::from("%Y-%m-%d %H:%M:%S%.6f %z")))
      .init();
  } else {
    fmt.without_time().init();
  }

Cargo.toml:

[dependencies]
eyre = "*"
tracing = "*"

[dependencies.tracing-subscriber]
version = "*"
features = ["env-filter", "fmt", "ansi", "chrono"]

记录到 journald

[1]

use tracing::{trace, debug, info, warn, error};
use tracing_subscriber::prelude::*;

fn main() {
  let journald = tracing_journald::layer().unwrap();
  tracing_subscriber::registry().with(journald).init();
  trace!(key="0.0", key2=0, "trace! key={}, key2={}", "0.0", 0);
  debug!(key="meow", key2=1, "debug! key={}, key2={}", "meow", 1);
  info!(key="nyan", key2=2, "info! key={}, key2={}", "nyan", 2);
  warn!(key="shhhh", key2=3, "warn! key={}, key2={}", "shhhh", 3);
  error!(key="喵!", key2=4, "error! key={}, key2={}", "喵!", 4);
}

参考资料