~qeef/wschat

ff1c59ba837aafdd6a4221d16c95d16010d1c6ba — Jiri Vlasak 3 years ago 6d83a92
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.
1 files changed, 35 insertions(+), 1 deletions(-)

M src/main.rs
M src/main.rs => src/main.rs +35 -1
@@ 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) {