Skip to content

Commit

Permalink
logging to files
Browse files Browse the repository at this point in the history
  • Loading branch information
JieningYu committed Apr 24, 2024
1 parent ff8b95d commit 2d25f1c
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 7 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/target
config.toml
/db
/logs
38 changes: 31 additions & 7 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ impl<Io: IoHandle> Clone for Global<Io> {
#[derive(Debug, Deserialize)]
struct Config {
db_path: PathBuf,
#[serde(default)]
log_path: Option<PathBuf>,
#[serde(default)]
log_level: Option<String>,
port: u32,

/// Root secret mapping.
Expand All @@ -53,26 +57,43 @@ struct Config {

#[tokio::main]
async fn main() {
tracing_subscriber::fmt::init();

const CONFIG_PATH: &str = "config.toml";
let config: Config = toml::from_str(&{
use std::io::Read;
let mut str = String::new();
std::fs::File::open("config.toml")
std::fs::File::open(CONFIG_PATH)
.unwrap()
.read_to_string(&mut str)
.unwrap();
str
})
.unwrap();
let port = config.port;

tracing_subscriber::fmt::init();
if let Some(path) = &config.log_path {
tracing_subscriber::fmt()
.with_max_level(
config
.log_level
.as_ref()
.and_then(|str| str.parse::<tracing::Level>().ok())
.unwrap_or(tracing::Level::INFO),
)
.with_writer(
std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(path)
.expect("failed to create log file"),
)
.init();
}

let port = config.port;
let mut paper_path = config.db_path.clone();
paper_path.push("papers");

let mut questions_path = config.db_path.clone();
questions_path.push("questions");

let config = Arc::new(config);

let state = Global {
Expand All @@ -88,7 +109,10 @@ async fn main() {
};

let router: Router<()> = Router::new()
.layer(TraceLayer::new_for_http())
.layer(
TraceLayer::new_for_http()
.on_request(tower_http::trace::DefaultOnRequest::new().level(tracing::Level::INFO)),
)
.route("/questions/new", post(question::new::<FsHandle>))
.route("/paper/post", post(paper::post::<FsHandle>))
.route("/paper/get", get(paper::get::<FsHandle>))
Expand Down
2 changes: 2 additions & 0 deletions src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ fn router() -> (Global<MemStorage>, Router) {
mng_get_papers_secret: "get_papers".to_owned(),
mng_approve_papers_secret: "approve_papers".to_owned(),
mng_reject_papers_secret: "reject_papers".to_owned(),
log_path: None,
log_level: None,
};

let state = Global {
Expand Down

0 comments on commit 2d25f1c

Please sign in to comment.