Skip to content

Commit

Permalink
Replaced println! macro with logger
Browse files Browse the repository at this point in the history
  • Loading branch information
dialogflowchatbot committed Jan 11, 2024
1 parent 195386f commit fadbdbe
Show file tree
Hide file tree
Showing 13 changed files with 39 additions and 81 deletions.
8 changes: 5 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "dialogflow"
version = "1.9.0"
version = "1.9.1"
edition = "2021"
homepage = "https://dialogflowchatbot.github.io/"
authors = ["dialogflowchatbot <[email protected]>"]
Expand Down Expand Up @@ -39,7 +39,9 @@ time = { version = "0.3", features = ["formatting"] }
tower-http = { version = "0.5", features = ["cors"] }
# typetag = "0.2"
tokio = { version = "1", features = ["fs", "io-util", "macros", "net", "rt", "rt-multi-thread", "signal", "time"] }
tracing-subscriber = "0.3"
# tracing-subscriber = "0.3"
log = "0.4.20"
env_logger = "0.10.1"
# triple_accel = "0.4.0"

[build-dependencies]
Expand Down Expand Up @@ -76,4 +78,4 @@ overflow-checks = false
opt-level = 3
codegen-units = 1
lto = true
panic = 'abort'
panic = 'abort'
9 changes: 4 additions & 5 deletions src/flow/rt/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ pub async fn clean_expired_session(
}
}
// sleep(Duration::from_millis(1800000)).await;
println!("Cleaning expired sessions");
log::info!("Cleaning expired sessions");
let r: Result<Option<Vec<ContextStatus>>> = db::query(TABLE, CONTEXT_KEY);
if let Ok(op) = r {
if let Some(mut d) = op {
Expand All @@ -140,18 +140,17 @@ pub async fn clean_expired_session(
if now - d[i].create_time > max_sess_dur_sec {
let val = d.remove(i);
if let Err(e) = db::remove(TABLE, val.session_id.as_str()) {
eprintln!("{:?}", e);
log::error!("Removing expired session {} failed {:?}", val.session_id, e);
}
println!("Removing expired session:{}", val.session_id);
} else {
i += 1;
}
}
if let Err(e) = db::write(TABLE, CONTEXT_KEY, &d) {
eprintln!("{:?}", e);
log::error!("{:?}", e);
}
}
Err(e) => eprintln!("{:?}", e),
Err(e) => log::error!("{:?}", e),
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/flow/rt/facade.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@ pub(crate) async fn answer(Json(mut req): Json<Request>) -> impl IntoResponse {
let r = executor::process(&mut req);
// println!("exec used time:{:?}", now.elapsed());
let res = to_res(r);
println!("Total response used time:{:?}", now.elapsed());
log::info!("Total response used time:{:?}", now.elapsed());
res
}
4 changes: 2 additions & 2 deletions src/flow/rt/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ impl RuntimeNode for TextNode {
// let now = std::time::Instant::now();
match replace_vars(&self.text, &req, ctx) {
Ok(answer) => response.answers.push(answer),
Err(e) => eprintln!("{:?}", e),
Err(e) => log::error!("{:?}", e),
};
add_next_node(ctx, &self.next_node_id);
// println!("TextNode used time:{:?}", now.elapsed());
Expand Down Expand Up @@ -226,7 +226,7 @@ impl RuntimeNode for ExternalHttpCallNode {
crate::external::http::dto::ResponseData::Bin(_) => {}
crate::external::http::dto::ResponseData::None => {}
},
Err(e) => eprintln!("{:?}", e),
Err(e) => log::error!("{:?}", e),
}
});
}
Expand Down
2 changes: 1 addition & 1 deletion src/flow/rt/node_dyn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ impl RuntimeNode for TextNode {
// let now = std::time::Instant::now();
match replace_vars(&self.text, &req, &ctx) {
Ok(answer) => response.answers.push(answer),
Err(e) => eprintln!("{:?}", e),
Err(e) => log::error!("{:?}", e),
};
add_next_node(ctx, &self.next_node_id);
// println!("TextNode used time:{:?}", now.elapsed());
Expand Down
2 changes: 1 addition & 1 deletion src/flow/rt/node_typetag.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ impl RuntimeNode for TextNode {
// let now = std::time::Instant::now();
match replace_vars(&self.text, &req, &ctx) {
Ok(answer) => response.answers.push(answer),
Err(e) => eprintln!("{:?}", e),
Err(e) => log::error!("{:?}", e),
};
add_next_node(ctx, &self.next_node_id);
// println!("TextNode used time:{:?}", now.elapsed());
Expand Down
10 changes: 6 additions & 4 deletions src/intent/crud.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,9 @@ pub(crate) async fn remove(Json(params): Json<IntentFormData>) -> impl IntoRespo
if let Ok(idx) = params.data.parse() {
let mut intents: Vec<Intent> = db::query(TABLE, INTENT_LIST_KEY).unwrap().unwrap();
intents.remove(idx);
db::write(TABLE, INTENT_LIST_KEY, &intents);
if let Err(e) = db::write(TABLE, INTENT_LIST_KEY, &intents) {
log::error!("Update intents list failed: {:?}", &e);
}
}
to_res(r)
}
Expand Down Expand Up @@ -203,7 +205,7 @@ pub(crate) async fn remove_keyword(Json(params): Json<IntentFormData>) -> impl I
.data
.parse::<usize>()
.map_err(|e| {
eprintln!("{:?}", e);
log::error!("{:?}", e);
Error::ErrorWithMessage(String::from("Invalid parameter"))
})
.and_then(|idx| {
Expand Down Expand Up @@ -248,7 +250,7 @@ pub(crate) async fn remove_regex(Json(params): Json<IntentFormData>) -> impl Int
.data
.parse::<usize>()
.map_err(|e| {
eprintln!("{:?}", e);
log::error!("{:?}", e);
Error::ErrorWithMessage(String::from("Invalid parameter"))
})
.and_then(|idx| {
Expand Down Expand Up @@ -292,7 +294,7 @@ pub(crate) async fn remove_phrase(Json(params): Json<IntentFormData>) -> impl In
.data
.parse::<usize>()
.map_err(|e| {
eprintln!("{:?}", e);
log::error!("{:?}", e);
Error::ErrorWithMessage(String::from("Invalid parameter"))
})
.and_then(|idx| {
Expand Down
58 changes: 8 additions & 50 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
use std::env;

use env_logger::{Builder as LoggerBuilder, Target};
// use jieba_rs::Jieba;
// use simsearch::{SearchOptions, SimSearch};
// use strsim::damerau_levenshtein as a;
Expand All @@ -8,57 +11,12 @@ use tokio::runtime::Builder;
use dialogflow::web::server::start_app;

fn main() {
/*
println!("{}", ((1.0 - 0.8) * 2_f32).ceil() as u32);
let options = SearchOptions::new().levenshtein(false);
let mut engine: SimSearch<&'static str> = SimSearch::new_with(options);
engine.insert("不喜欢1", "我 不喜欢 这个 产品");
// engine.insert("不喜欢2", "我 讨厌");
engine.insert("喜欢1", "我 超级 喜欢 另外 一个 产品");
// engine.insert("喜欢2", "我 爱 这个");
// engine.insert("喜欢1", "我 喜欢 这个 产品");
// engine.insert("闲聊", "哈哈哈哈");
let results: Vec<&'static str> = engine.search("喜欢");
println!("{:?}", results);
// assert_eq!(results, &[1]);
println!("{:?}", damerau_levenshtein("我喜欢", "喜欢"));
println!("{:?}", damerau_levenshtein("我不喜欢", "喜欢"));
println!("{:?}", damerau_levenshtein("我喜欢这个产品", "喜欢"));
println!("{:?}", damerau_levenshtein("我不喜欢这个产品", "喜欢"));
let token = "我 超级 喜欢 这个 产品";
let pattern_token = "喜欢";
let len = std::cmp::max(token.len(), pattern_token.len()) as f64;
println!("len {}", len);
let k = ((1.0 - 0.8) * len).ceil() as u32;
println!("k {}", k);
println!(
"zz {:?}",
levenshtein_simd_k(token.as_bytes(), pattern_token.as_bytes(), 3)
);
// println!("{:?}", levenshtein("i like it", "i like"));
// println!("{:?}", levenshtein("i don't like it", "i like"));
// let buf = std::io::Cursor::new(b"不喜欢");
let mut jieba = Jieba::new();
jieba.add_word("不喜欢", None, None);
let words = jieba.cut("我不喜欢这个产品", false);
println!("{:?}", words);
println!("{:?}", a("我喜欢", "喜欢"));
println!("{:?}", a("我不喜欢", "喜欢"));
println!("{:?}", a("我超级喜欢这个产品", "喜欢"));
println!("{:?}", a("我不喜欢这个产品", "喜欢"));
println!("{:?}", a("产品", "喜欢"));
*/

// dialogflow::web::t1();
env::set_var("RUST_LOG", "INFO");
let mut builder = LoggerBuilder::from_default_env();
builder.target(Target::Stdout).format_module_path(false).format_target(false)
.format_indent(None);
builder.init();

let runtime = Builder::new_multi_thread()
.worker_threads(4)
Expand Down
2 changes: 1 addition & 1 deletion src/man/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ pub(crate) async fn save(Json(data): Json<Settings>) -> impl IntoResponse {
pub(crate) fn save_settings(data: &Settings) -> Result<()> {
let addr = format!("{}:{}", data.ip, data.port);
let _: SocketAddr = addr.parse().map_err(|_| {
eprintln!("Saving invalid listen IP: {}", &addr);
log::error!("Saving invalid listen IP: {}", &addr);
Error::ErrorWithMessage(String::from("lang.settings.invalidIp"))
})?;
db::write(TABLE, SETTINGS_KEY, &data)
Expand Down
2 changes: 1 addition & 1 deletion src/variable/dto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ impl Variable {
_ => None,
},
Err(e) => {
eprintln!("{:?}", e);
log::error!("{:?}", e);
None
}
},
Expand Down
2 changes: 0 additions & 2 deletions src/web/asset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,4 @@ HashMap::from([
("/assets/step8-4ffd1e3d.png", 23),
("/assets/step9-772a025e.png", 24),
("/favicon.ico", 25),
("/", 26),
("/index.html", 26),
])});
1 change: 0 additions & 1 deletion src/web/asset.txt
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,4 @@
(include_bytes!(r#"..\resources\assets/assets\step8-4ffd1e3d.png.gz"#), ""),
(include_bytes!(r#"..\resources\assets/assets\step9-772a025e.png.gz"#), ""),
(include_bytes!(r#"..\resources\assets/favicon.ico.gz"#), "image/x-icon"),
(include_bytes!(r#"..\resources\assets/index.html.gz"#), "text/html; charset=utf-8"),
]
18 changes: 9 additions & 9 deletions src/web/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const ASSETS: &[(&[u8], &str)] = &include!("asset.txt");

pub(crate) static IS_EN: Lazy<bool> = Lazy::new(|| {
let language = get_lang();
println!("Your OS language is: {}", language);
// println!("Your OS language is: {}", language);
language[0..2].eq("en")
});

Expand Down Expand Up @@ -69,7 +69,7 @@ pub async fn start_app() {
#[cfg(target_os = "windows")]
let _ = colored::control::set_virtual_terminal(true).unwrap();

println!(
log::info!(
" --> {} {}{}:{}",
if *IS_EN {
"Please open a browser and visit"
Expand All @@ -80,10 +80,10 @@ pub async fn start_app() {
settings.ip.bright_green(),
settings.port.to_string().blue()
);
println!("Current version: {}", VERSION);
println!("Visiting https://dialogflowchatbot.github.io/ for the latest releases");
log::info!("Current version: {}", VERSION);
log::info!("Visiting https://dialogflowchatbot.github.io/ for the latest releases");

println!(
log::info!(
" --> Press {} to terminate this application",
"Ctrl+C".bright_red()
);
Expand Down Expand Up @@ -200,7 +200,7 @@ fn convert_version(ver: &str) -> u64 {
v.push_str("0");
}
v.push_str(arr[2]);
// println!("vernum={}", &v);
// log::info!("vernum={}", &v);
v.parse().expect("Wrong version")
}

Expand Down Expand Up @@ -267,15 +267,15 @@ async fn shutdown_signal(sender: tokio::sync::oneshot::Sender<()>) {

match sender.send(()) {
Ok(_) => {}
Err(_) => println!("中断 ctx 失败"),
Err(_) => log::info!("中断 ctx 失败"),
};

let m = if *IS_EN {
"This program has been terminated"
} else {
"应用已退出"
};
println!("{}", m);
log::info!("{}", m);
}

#[derive(Serialize)]
Expand Down Expand Up @@ -310,7 +310,7 @@ where
// simd_json::to_string(&res).unwrap()
}
};
// println!("serialize used time:{:?}", now.elapsed());
// log::info!("serialize used time:{:?}", now.elapsed());
let mut header_map = HeaderMap::new();
header_map.insert(header::CONTENT_TYPE, "application/json".parse().unwrap());
(StatusCode::OK, header_map, data)
Expand Down

0 comments on commit fadbdbe

Please sign in to comment.