From ff1c59ba837aafdd6a4221d16c95d16010d1c6ba Mon Sep 17 00:00:00 2001 From: Jiri Vlasak Date: Mon, 30 Nov 2020 17:25:15 +0100 Subject: [PATCH] Add logging when env var supported You need to specify LOG_DIR environment variable in order to log messages to the directory. The messages are stored on day basis to the file of the format YYYY-MM-DD. --- src/main.rs | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index 1cfd50d..2d105fc 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,8 +3,12 @@ use futures::{FutureExt, StreamExt}; use jsonwebtoken::{DecodingKey, Validation, Algorithm}; use serde::{Deserialize, Serialize}; use serde_json::Value; -use std::env; use std::collections::HashMap; +use std::env; +use std::fs::File; +use std::fs::OpenOptions; +use std::io::Write; +use std::path::Path; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; use tokio::sync::RwLock; @@ -83,6 +87,36 @@ async fn send_msg(msg: Message, clients: &Clients) { for (&_id, tx) in clients.read().await.iter() { tx.send(Ok(Message::text(msg.to_string()))); } + match env::var("LOG_DIR") { + Ok(dname) => { + let today = Utc::now().format("%Y-%m-%d").to_string(); + let mut dname = dname; + dname.push_str("/"); + dname.push_str(&today); + let path = Path::new(&dname); + let mut file = match OpenOptions::new() + .append(true) + .open(&path) { + Ok(f) => f, + Err(_) => { + let mut err_msg = String::from("can't create "); + err_msg.push_str(&dname); + File::create(&path).expect(&err_msg) + }, + }; + let mut to_write = msg; + match to_write.get("jwt") { + Some(_) => { + to_write["jwt"] = serde_json::json!("..."); + }, + None => {}, + } + let mut to_write = to_write.to_string(); + to_write.push_str("\n"); + file.write_all(to_write.as_bytes()).expect("write failed"); + }, + Err(_) => {}, + } } async fn close_client(id: usize, clients: &Clients) { -- 2.45.2