From 182fd47e1677a116b377dbb900386b9d6b1cf110 Mon Sep 17 00:00:00 2001 From: taynpg Date: Mon, 24 Feb 2025 17:43:58 +0800 Subject: [PATCH] =?UTF-8?q?fix=EF=BC=9A=E4=BF=AE=E6=AD=A3=E6=81=A2?= =?UTF-8?q?=E5=A4=8Dlog=E6=89=93=E5=8D=B0=E5=90=8E=EF=BC=8C=E6=9C=AA?= =?UTF-8?q?=E4=B8=8A=E9=94=81=E7=9A=84=E9=97=AE=E9=A2=98=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- client/client.cpp | 164 +++++++++++++++++++++++----------------------- client/config.cpp | 6 +- client/main.cpp | 28 ++++---- net/net_base.cpp | 18 ++--- server/main.cpp | 8 +-- server/server.cpp | 56 ++++++++-------- util/util.h | 28 ++++++++ 7 files changed, 168 insertions(+), 140 deletions(-) diff --git a/client/client.cpp b/client/client.cpp index 5705b89..39cfb18 100644 --- a/client/client.cpp +++ b/client/client.cpp @@ -52,7 +52,7 @@ void CClient::run(const std::string& ip, const std::string& port) { th_run_ = true; if (!client_->connect(ip, port)) { - log_->info("{} connect err.", __FUNCTION__); + TLOGI(log_, "{} connect err.", __FUNCTION__); return; } client_->register_func([&](CFrameBuffer* buf) { handle_frame(buf); }); @@ -64,9 +64,9 @@ void CClient::run(const std::string& ip, const std::string& port) bf->type_ = TYPE_GET_ID; send_frame(bf); delete bf; - log_->info("version: {}", VERSION_NUM); - log_->info("opensource: {}", VERSION_URL); - log_->warn("SupportCmd:Get|Up|Down|Cancel|Update"); + TLOGI(log_, "version: {}", VERSION_NUM); + TLOGI(log_, "opensource: {}", VERSION_URL); + TLOGW(log_, "SupportCmd:Get|Up|Down|Cancel|Update"); fc_append('|'); while (1) { @@ -75,7 +75,7 @@ void CClient::run(const std::string& ip, const std::string& port) break; } if (!th_run_ || !client_->is_normal()) { - log_->warn("The link has been closed and cannot be continued. It will automatically exit."); + TLOGW(log_, "The link has been closed and cannot be continued. It will automatically exit."); break; } std::string cmd_input(readline); @@ -97,7 +97,7 @@ void CClient::run(const std::string& ip, const std::string& port) } auto vec = COfStr::split(cmd_input, " "); if (vec.size() < 2) { - log_->error("No matched cmd, May be param size incorrect."); + TLOGE(log_, "No matched cmd, May be param size incorrect."); continue; } std::string param(cmd_input); @@ -116,11 +116,11 @@ void CClient::run(const std::string& ip, const std::string& port) up_task(param); continue; } - log_->error("No matched cmd, May be param size incorrect."); + TLOGE(log_, "No matched cmd, May be param size incorrect."); } client_->disconnect(); thread.join(); - log_->info("{} exit.", __FUNCTION__); + TLOGI(log_, "{} exit.", __FUNCTION__); } bool CClient::get_task_list() @@ -133,14 +133,14 @@ bool CClient::get_task_list() bool CClient::down_task(const std::string& param) { if (downloading_) { - log_->warn("Have Task Downloading, Please wait....."); + TLOGW(log_, "Have Task Downloading, Please wait....."); return false; } std::string relative_path; auto v = COfStr::split(param, " "); if (v.size() < 1) { - log_->error("param size not enough."); + TLOGE(log_, "param size not enough."); return false; } if (v.size() > 1) { @@ -148,12 +148,12 @@ bool CClient::down_task(const std::string& param) } auto id = std::stoi(v[0]); if (!task_list_.count(id)) { - log_->error("No matched id[{}] in task list.", id); + TLOGE(log_, "No matched id[{}] in task list.", id); return false; } if (task_list_[id]->id == own_id_) { - log_->warn("You can't down your own file!!!"); + TLOGW(log_, "You can't down your own file!!!"); return false; } @@ -161,7 +161,7 @@ bool CClient::down_task(const std::string& param) down_ = std::make_shared(); if (vec.empty()) { - log_->warn("No files List, Please Check!"); + TLOGW(log_, "No files List, Please Check!"); return false; } @@ -182,7 +182,7 @@ bool CClient::up_task(const std::string& param) std::lock_guard lock(mutex_); for (const auto& item : up_) { if (item.second->trans_state_ == TRANS_REDAY || item.second->trans_state_ == TRANS_ING) { - log_->warn("Have Task Upping, Please wait!"); + TLOGW(log_, "Have Task Upping, Please wait!"); return false; } } @@ -190,19 +190,19 @@ bool CClient::up_task(const std::string& param) std::vector list{}; if (!CFileOpr::get_file_list(param, list, log_)) { - log_->error("abort do up task."); + TLOGE(log_, "abort do up task."); return false; } std::string msg; for (const auto& item : list) { if (!fs::exists(item)) { - log_->error("File {} not exist, please check.", item); + TLOGE(log_, "File {} not exist, please check.", item); return false; } if (!fs::is_regular_file(item)) { - log_->error("Only Support Up File, But directory.", item); + TLOGE(log_, "Only Support Up File, But directory.", item); return false; } @@ -213,7 +213,7 @@ bool CClient::up_task(const std::string& param) } } if (msg.empty()) { - log_->warn("{} msg empty.", __FUNCTION__); + TLOGW(log_, "{} msg empty.", __FUNCTION__); return false; } @@ -235,7 +235,7 @@ bool CClient::cancel_task() std::lock_guard lock(mutex_); for (const auto& item : up_) { if (item.second->trans_state_ == TRANS_REDAY || item.second->trans_state_ == TRANS_ING) { - log_->warn("Have Task Upping, Please wait!"); + TLOGW(log_, "Have Task Upping, Please wait!"); return false; } } @@ -265,10 +265,10 @@ bool CClient::down_one_file(const std::string& id, const std::string& file, cons down_->cur_file_ = fs::path(back_local_dir).append(remote_file.filename().string()).string(); } - log_->warn("Start Down => {} To {}", down_->cur_remote_file_, down_->cur_file_); + TLOGW(log_, "Start Down => {} To {}", down_->cur_remote_file_, down_->cur_file_); down_->file_.open(down_->cur_file_, std::ios::out | std::ios::binary); if (!down_->file_.is_open()) { - log_->error("Open {} Failed.", down_->cur_file_); + TLOGE(log_, "Open {} Failed.", down_->cur_file_); return false; } @@ -279,7 +279,7 @@ bool CClient::down_one_file(const std::string& id, const std::string& file, cons buf->data_ = new char[file.size() + 1]; buf->len_ = std::snprintf(buf->data_, file.size() + 1, "%s", file.data()); if (!send_frame(buf.get())) { - log_->error("{} request open file [{}] send failed.", __FUNCTION__, down_->cur_remote_file_); + TLOGE(log_, "{} request open file [{}] send failed.", __FUNCTION__, down_->cur_remote_file_); down_->cur_remote_id_.clear(); down_->cur_remote_file_.clear(); return false; @@ -296,7 +296,7 @@ bool CClient::down_one_file(const std::string& id, const std::string& file, cons CTransProtocal::display_progress(percent); } if (!th_run_) { - log_->error("Interrup When Receive File."); + TLOGE(log_, "Interrup When Receive File."); report_trans_ret(TRANS_FAILED); return false; } @@ -307,10 +307,10 @@ bool CClient::down_one_file(const std::string& id, const std::string& file, cons } fc_enable_cur(); if (cur_down_size_ > 0 && cur_file_size_ == cur_down_size_) { - log_->warn("down one file success, total:[{}/{}]", cur_down_size_, cur_file_size_); + TLOGW(log_, "down one file success, total:[{}/{}]", cur_down_size_, cur_file_size_); return true; } else { - log_->warn("down one file {} failed.", down_->cur_file_); + TLOGW(log_, "down one file {} failed.", down_->cur_file_); if (!down_->file_.is_open()) { down_->file_.close(); fs::remove(down_->cur_file_); @@ -359,24 +359,24 @@ bool CClient::request_update_list(const std::string& param) { auto tvec = COfStr::split(param, " "); if (tvec.size() < 2) { - log_->error("{} invalid param format [{}]", __FUNCTION__, param); + TLOGE(log_, "{} invalid param format [{}]", __FUNCTION__, param); return false; } int index = std::stoi(tvec[0]); std::string list_file = tvec[1]; if (downloading_) { - log_->warn("Have Task Downloading, Please wait....."); + TLOGW(log_, "Have Task Downloading, Please wait....."); return false; } if (!task_list_.count(index)) { - log_->error("No Index Found {}.", index); + TLOGE(log_, "No Index Found {}.", index); return false; } const auto& sr = task_list_[index]; if (sr->id == own_id_) { - log_->warn("You can't update your own file!!!"); + TLOGW(log_, "You can't update your own file!!!"); return false; } @@ -384,7 +384,7 @@ bool CClient::request_update_list(const std::string& param) std::string list_file_full = COfPath::to_full(list_file); std::ifstream in(list_file_full); if (!in.is_open()) { - log_->error("Can't Open File:{}", list_file_full); + TLOGE(log_, "Can't Open File:{}", list_file_full); return false; } std::istreambuf_iterator iterf(in); @@ -411,11 +411,11 @@ bool CClient::request_update_list(const std::string& param) if (v.size() >= 2) { auto pr = variable_handle(list_file_full, v[0], true); if (!fs::exists(pr)) { - log_->error("file {} not exist.", pr); + TLOGE(log_, "file {} not exist.", pr); valid = false; break; } - log_->info("--->check pass {}:{}", line, pr); + TLOGI(log_, "--->check pass {}:{}", line, pr); mre[line++] = pr + "|" + v[1]; continue; } @@ -424,13 +424,13 @@ bool CClient::request_update_list(const std::string& param) } if (!valid) { - log_->error("Judge List File {} Format Not Passed.", list_file_full); + TLOGE(log_, "Judge List File {} Format Not Passed.", list_file_full); return false; } auto handel_ret = handle_user_select(mre); if (handel_ret.empty()) { - log_->error("handle_user_select not pass, abort action!"); + TLOGE(log_, "handle_user_select not pass, abort action!"); return false; } @@ -446,7 +446,7 @@ bool CClient::request_update_list(const std::string& param) buf->tid_ = task_list_[index]->id; if (!send_frame(buf.get())) { - log_->error("Send Failed {}", __LINE__); + TLOGE(log_, "Send Failed {}", __LINE__); return false; } return true; @@ -466,17 +466,17 @@ bool CClient::check_update_list(const std::string& content, std::maperror("Size not 2 {}", item); + TLOGE(log_, "Size not 2 {}", item); valid = false; break; } auto pr = variable_handle("", vi[1], false); if (!fs::exists(pr)) { valid = false; - log_->error("Not exist {}", pr); + TLOGE(log_, "Not exist {}", pr); break; } - log_->info("---> check pass {}", pr); + TLOGI(log_, "---> check pass {}", pr); #ifdef _WIN32 files[CCodec::ansi_to_u8(vi[0])] = CCodec::ansi_to_u8(pr); #else @@ -500,10 +500,10 @@ bool CClient::down_update_file(const std::map& files) } if (suc) { buf->type_ = TYPE_DONE_UPDATE_LIST; - log_->info("Do Task From Remote {} Done!", buf->tid_); + TLOGI(log_, "Do Task From Remote {} Done!", buf->tid_); } else { buf->type_ = TYPE_FAILED_UPDATE_LIST; - log_->info("Do Task From Remote {} Failed!", buf->tid_); + TLOGI(log_, "Do Task From Remote {} Failed!", buf->tid_); } send_frame(buf.get()); return suc; @@ -514,7 +514,7 @@ bool CClient::send_frame(CFrameBuffer* buf) char* out_buf{}; int out_len{}; if (!CTransProtocal::pack(buf, &out_buf, out_len)) { - log_->error("{} pack failed.", __FUNCTION__); + TLOGE(log_, "{} pack failed.", __FUNCTION__); return false; } std::lock_guard lock(send_mut_); @@ -529,12 +529,12 @@ bool CClient::send_frame(CFrameBuffer* buf) void CClient::handle_frame(CFrameBuffer* buf) { if (buf == nullptr) { - log_->error("{} nullptr.", __FUNCTION__); + TLOGE(log_, "{} nullptr.", __FUNCTION__); return; } switch (buf->type_) { case TYPE_GET_ID: { - log_->debug("Your ID:{}", buf->tid_); + TLOGD(log_, "Your ID:{}", buf->tid_); own_id_ = buf->tid_; break; } @@ -552,9 +552,9 @@ void CClient::handle_frame(CFrameBuffer* buf) if (real.find('[') == std::string::npos) { if (num < 20) { #ifdef _WIN32 - log_->info("FILE ==> {}", CCodec::u8_to_ansi(real)); + TLOGI(log_, "FILE ==> {}", CCodec::u8_to_ansi(real)); #else - log_->info("FILE ==> {}", real); + TLOGI(log_, "FILE ==> {}", real); #endif } task_list_[index]->files.push_back(real); @@ -576,13 +576,13 @@ void CClient::handle_frame(CFrameBuffer* buf) task_list_[index]->id = id; } if (num < 20) { - log_->debug("*****************************************"); - log_->info("{}", real); + TLOGD(log_, "*****************************************"); + TLOGI(log_, "{}", real); } } } if (num >= 20) { - log_->warn("Too Many Files [{}], Only Display 20.", num); + TLOGW(log_, "Too Many Files [{}], Only Display 20.", num); } break; } @@ -596,7 +596,7 @@ void CClient::handle_frame(CFrameBuffer* buf) down_->file_.write(buf->data_, buf->len_); if (down_->file_.fail()) { report_trans_ret(TRANS_FAILED); - log_->warn("no matched write and data. {}", buf->len_); + TLOGW(log_, "no matched write and data. {}", buf->len_); } cur_down_size_ += buf->len_; } @@ -615,11 +615,11 @@ void CClient::handle_frame(CFrameBuffer* buf) up_[buf->fid_]->file_.open(up_[buf->fid_]->cur_file_, std::ios::in | std::ios::binary); up_[buf->fid_]->trans_state_ = TRANS_REDAY; if (!up_[buf->fid_]->file_.is_open()) { - log_->error("Ready Send File {} Open Failed.", up_[buf->fid_]->cur_file_); + TLOGE(log_, "Ready Send File {} Open Failed.", up_[buf->fid_]->cur_file_); buf->type_ = TYPE_OPEN_FAILED; std::swap(buf->tid_, buf->fid_); if (!send_frame(buf)) { - log_->error("Send Failed {}.", __LINE__); + TLOGE(log_, "Send Failed {}.", __LINE__); break; } break; @@ -636,7 +636,7 @@ void CClient::handle_frame(CFrameBuffer* buf) #ifdef _WIN32 #else if (down_ && down_->remote_plat == 1) { - log_->info("recovery permissions {}.", down_->permissions); + TLOGI(log_, "recovery permissions {}.", down_->permissions); fs::perms perms = static_cast(down_->permissions); fs::permissions(down_->cur_file_, perms); } @@ -644,7 +644,7 @@ void CClient::handle_frame(CFrameBuffer* buf) break; } case TYPE_OPEN_FAILED: { - log_->error("Remote {} Open File Failed.", buf->fid_); + TLOGE(log_, "Remote {} Open File Failed.", buf->fid_); if (down_) { down_->trans_state_ = TRANS_FAILED; } @@ -654,7 +654,7 @@ void CClient::handle_frame(CFrameBuffer* buf) if (buf->mark_) { std::lock_guard lock(mutex_); if (!up_.count(buf->fid_)) { - log_->warn("Offline no match."); + TLOGW(log_, "Offline no match."); break; } auto t = up_[buf->fid_]; @@ -662,7 +662,7 @@ void CClient::handle_frame(CFrameBuffer* buf) break; } if (downloading_ && !down_->cur_remote_file_.empty()) { - log_->warn("Stop Down {} From {}.", down_->cur_remote_file_, buf->fid_); + TLOGW(log_, "Stop Down {} From {}.", down_->cur_remote_file_, buf->fid_); } report_trans_ret(TRANS_FAILED); break; @@ -670,7 +670,7 @@ void CClient::handle_frame(CFrameBuffer* buf) case TYPE_REQUEST_UPDATE_LIST: { std::map files; if (down_ && down_->trans_state_ == TRANS_REDAY) { - log_->warn("Update Busy......, Ignore {}", buf->fid_); + TLOGW(log_, "Update Busy......, Ignore {}", buf->fid_); buf->type_ = TYPE_BUSY_UPDATE_LIST; } else { std::string content(buf->data_, buf->len_); @@ -682,14 +682,14 @@ void CClient::handle_frame(CFrameBuffer* buf) } std::swap(buf->tid_, buf->fid_); if (!send_frame(buf)) { - log_->error("Send Failed {}.", __LINE__); + TLOGE(log_, "Send Failed {}.", __LINE__); break; } if (buf->type_ != TYPE_CONFIRM_UPDATE_LIST) { break; } list_serve_id_ = buf->tid_; - log_->debug("Do Task From Remote {}.", buf->tid_); + TLOGD(log_, "Do Task From Remote {}.", buf->tid_); if (update_list_th_.joinable()) { update_list_th_.join(); } @@ -697,35 +697,35 @@ void CClient::handle_frame(CFrameBuffer* buf) break; } case TYPE_CONFIRM_UPDATE_LIST: { - log_->info("remote {} check {} passed!", buf->fid_, list_file_); + TLOGI(log_, "remote {} check {} passed!", buf->fid_, list_file_); break; } case TYPE_UNCONFIRM_UPDATE_LIST: { - log_->error("remote {} check {} not passed!", buf->fid_, list_file_); + TLOGE(log_, "remote {} check {} not passed!", buf->fid_, list_file_); break; } case TYPE_DONE_UPDATE_LIST: { - log_->info("remote {} do task {} success!", buf->fid_, list_file_); + TLOGI(log_, "remote {} do task {} success!", buf->fid_, list_file_); break; } case TYPE_FAILED_UPDATE_LIST: { - log_->info("remote {} do task {} failed!", buf->fid_, list_file_); + TLOGI(log_, "remote {} do task {} failed!", buf->fid_, list_file_); break; } case TYPE_BUSY_UPDATE_LIST: { - log_->info("remote {} are busy, will not exec task {}", buf->fid_, list_file_); + TLOGI(log_, "remote {} are busy, will not exec task {}", buf->fid_, list_file_); break; } case TYPE_FILE_INFO: { std::string str_size(buf->data_, buf->len_); auto vec = COfStr::split(str_size, ","); if (vec.size() < 3) { - log_->error("invalid file information:{}", str_size); + TLOGE(log_, "invalid file information:{}", str_size); break; } long long size = std::stoll(vec[1]); std::string show_str = OfUtil::get_file_size(size); - log_->info("Ready Down Size: {}, permissions:{}", show_str, vec[2]); + TLOGI(log_, "Ready Down Size: {}, permissions:{}", show_str, vec[2]); if (down_) { down_->permissions = static_cast(std::stoul(vec[2])); down_->remote_plat = static_cast(std::stoul(vec[0])); @@ -745,13 +745,13 @@ void CClient::send_file_data_th(const char* keys) { std::lock_guard lock(mutex_); if (!up_.count(str_key)) { - log_->error("{} no matched key.", __FUNCTION__); + TLOGE(log_, "{} no matched key.", __FUNCTION__); return; } t = up_[str_key]; } - log_->info("Start Trans File {} To {}", t->cur_file_, str_key); + TLOGI(log_, "Start Trans File {} To {}", t->cur_file_, str_key); std::shared_ptr buf = std::make_shared(); buf->data_ = new char[g_BuffSize]{}; buf->tid_ = str_key; @@ -778,12 +778,12 @@ void CClient::send_file_data_th(const char* keys) #endif std::string info_result = plat + "," + str_size + "," + str_perm; - log_->info("To {} File Size: {} [{}], permissions:{}", str_key, ofen::OfUtil::get_file_size(size), size, - str_perm); + TLOGI(log_, "To {} File Size: {} [{}], permissions:{}", str_key, ofen::OfUtil::get_file_size(size), size, + str_perm); buf->len_ = std::snprintf(buf->data_, g_BuffSize, "%s", info_result.c_str()); if (!send_frame(buf.get())) { report_trans_ret(TRANS_FAILED, str_key); - log_->error("Stop Trans {} To {} failed.", t->cur_file_, str_key); + TLOGE(log_, "Stop Trans {} To {} failed.", t->cur_file_, str_key); return; } buf->type_ = TYPE_TRANS_FILE; @@ -791,7 +791,7 @@ void CClient::send_file_data_th(const char* keys) while (!t->file_.eof()) { if (t->trans_state_ == TRANS_BREAK) { - log_->warn("Stop Trans {} To {} failed.", t->cur_file_, str_key); + TLOGW(log_, "Stop Trans {} To {} failed.", t->cur_file_, str_key); report_trans_ret(TRANS_FAILED, str_key); return; } @@ -799,7 +799,7 @@ void CClient::send_file_data_th(const char* keys) buf->len_ = t->file_.gcount(); if (!send_frame(buf.get())) { report_trans_ret(TRANS_FAILED, str_key); - log_->error("Stop Trans {} To {} failed.", t->cur_file_, str_key); + TLOGE(log_, "Stop Trans {} To {} failed.", t->cur_file_, str_key); return; } // std::this_thread::sleep_for(std::chrono::milliseconds(10)); @@ -807,10 +807,10 @@ void CClient::send_file_data_th(const char* keys) buf->type_ = TYPE_TRANS_DONE; if (!send_frame(buf.get())) { - log_->error("send_file_data_th send DONE failed."); + TLOGE(log_, "send_file_data_th send DONE failed."); } report_trans_ret(TRANS_DONE, str_key); - log_->debug("Trans File {} To {} Done !!!", t->cur_file_, str_key); + TLOGD(log_, "Trans File {} To {} Done !!!", t->cur_file_, str_key); } void CClient::hearts() @@ -820,7 +820,7 @@ void CClient::hearts() while (th_run_) { sleep_.sleep(); if (th_run_ && !send_frame(buf.get())) { - log_->error("{} send failed.", __FUNCTION__); + TLOGE(log_, "{} send failed.", __FUNCTION__); th_run_ = false; } } @@ -861,7 +861,7 @@ std::string CClient::handle_user_select(const std::unordered_mapinfo("numbers by space, or '0' use all, 'end' to quit: "); + TLOGI(log_, "numbers by space, or '0' use all, 'end' to quit: "); std::getline(std::cin, input); if (input == "end") { @@ -888,11 +888,11 @@ std::string CClient::handle_user_select(const std::unordered_maperror("Invalid input, please enter valid numbers or '0' for all."); + TLOGE(log_, "Invalid input, please enter valid numbers or '0' for all."); break; } } catch (const std::exception& e) { - log_->error("Invalid input, please enter valid numbers or '0' for all."); + TLOGE(log_, "Invalid input, please enter valid numbers or '0' for all."); break; } } @@ -933,18 +933,18 @@ bool CFileOpr::get_file_list(const std::string& input, std::vector& if (ret.find("?") != std::string::npos || ret.find("*") != std::string::npos) { auto fv = COfPath::match_files(ret); for (const auto& v : fv) { - log->info("match file: {}", v); + TLOGI(log, "match file: {}", v); } std::string cof; while (true) { - log->info("Detected regex's file (num = {}), please confirm if it is correct? ", fv.size()); - log->warn("support input in [y,Y,end]", fv.size()); + TLOGI(log, "Detected regex's file (num = {}), please confirm if it is correct? ", fv.size()); + TLOGW(log, "support input in [y,Y,end]", fv.size()); std::getline(std::cin, cof); if (cof == "y" || cof == "Y") { for (const auto& v : fv) { out.push_back(v); } - log->debug("OK, Done!"); + TLOGD(log, "OK, Done!"); break; } if (cof == "end") { diff --git a/client/config.cpp b/client/config.cpp index b8feb9d..84f8e8b 100644 --- a/client/config.cpp +++ b/client/config.cpp @@ -24,7 +24,7 @@ bool CServerConfig::baseInit() } SI_Error ret = ini_handle_.LoadFile(config_path_.c_str()); if (ret != SI_OK) { - log_->error("Load Ini [{}] Failed.", config_path_); + TLOGE(log_, "Load Ini [{}] Failed.", config_path_); return false; } init_ = true; @@ -36,7 +36,7 @@ bool CServerConfig::read_ini(std::vector& set) assert(init_ == true); long groups = ini_handle_.GetLongValue("BASE", "GROUPS"); if (groups < 1) { - log_->error("GROUPS num < 1."); + TLOGE(log_, "GROUPS num < 1."); return false; } set.clear(); @@ -106,7 +106,7 @@ bool CServerConfig::get_ini(const std::vector& set, long num, TransmS void CServerConfig::gen_default_ini(const std::string& path) { - log_->warn("Gen Default Setting Ini in [{}].", path); + TLOGW(log_, "Gen Default Setting Ini in [{}].", path); ini_handle_.LoadFile(path.c_str()); ini_handle_.SetLongValue("BASE", "GROUPS", 1); ini_handle_.SetValue("GROUP0", "IP", "127.0.0.1"); diff --git a/client/main.cpp b/client/main.cpp index 5467e11..7029df7 100644 --- a/client/main.cpp +++ b/client/main.cpp @@ -54,7 +54,7 @@ bool exec_cmd(const CmdParam& param, bool& run) return false; } for (const auto& item : set) { - g_Logger->info("{} => {}:{}", item.group, item.ip, item.port); + TLOGI(g_Logger, "{} => {}:{}", item.group, item.ip, item.port); } return true; } @@ -63,34 +63,34 @@ bool exec_cmd(const CmdParam& param, bool& run) return true; } if (!param.appendValue.empty() && !param.removeValue.empty()) { - g_Logger->error("append and remove can't simultaneous operate!"); + TLOGW(g_Logger, "append and remove can't simultaneous operate!"); return false; } if (!param.appendValue.empty()) { std::regex rg(R"(([^:]+):(\d+))"); std::smatch match; if (!std::regex_search(param.appendValue, match, rg)) { - g_Logger->error("append invalid format!"); + TLOGW(g_Logger, "append invalid format!"); return false; } std::string ip = match[1].str(); std::string port = match[2].str(); if (!g_Config->append_ini(ip, std::stol(port))) { - g_Logger->error("add {}:{} failed.", ip, port); + TLOGW(g_Logger, "add {}:{} failed.", ip, port); return false; } - g_Logger->info("add {}:{} success.", ip, port); + TLOGI(g_Logger, "add {}:{} success.", ip, port); return true; } if (!param.removeValue.empty()) { if (!g_Config->remove_ini(std::stol(param.removeValue))) { - g_Logger->error("remove config num=[{}] failed, please check!", param.removeValue); + TLOGW(g_Logger, "remove config num=[{}] failed, please check!", param.removeValue); return false; } - g_Logger->info("remove config num=[{}] success!", param.removeValue); + TLOGI(g_Logger, "remove config num=[{}] success!", param.removeValue); return true; } - g_Logger->error("not matched!", param.removeValue); + TLOGW(g_Logger, "not matched!", param.removeValue); return false; } @@ -118,7 +118,7 @@ int main(int argc, char* argv[]) return 0; } if (!exec_cmd(param, run)) { - g_Logger->error("exec_cmd failed!"); + TLOGW(g_Logger, "exec_cmd failed!"); return -1; } if (!run) { @@ -131,14 +131,14 @@ int main(int argc, char* argv[]) } TransmSet use; if (!g_Config->get_ini(set, param.use_config, use)) { - g_Logger->error("Not found config by num:[{}]", param.use_config); + TLOGW(g_Logger, "Not found config by num:[{}]", param.use_config); return -1; } - g_Logger->info("Build At {} {} under {} on {}", __DATE__, __TIME__, VERSION_GIT_COMMIT, - VERSION_GIT_BRANCH); - g_Logger->info("use ip => [{}], port => [{}]", use.ip, use.port); + TLOGI(g_Logger, "Build At {} {} under {} on {}", __DATE__, __TIME__, VERSION_GIT_COMMIT, + VERSION_GIT_BRANCH); + TLOGI(g_Logger, "use ip => [{}], port => [{}]", use.ip, use.port); CClient client(g_Logger); client.run(use.ip, std::to_string(use.port)); - g_Logger->info("exit =========="); + TLOGI(g_Logger, "exit =========="); return 0; } \ No newline at end of file diff --git a/net/net_base.cpp b/net/net_base.cpp index 0870509..741748b 100644 --- a/net/net_base.cpp +++ b/net/net_base.cpp @@ -13,11 +13,11 @@ bool CTcpClient::connect(const std::string& host, const std::string& port) asio::ip::tcp::resolver resolver(io_context_); asio::ip::tcp::resolver::results_type endpoints = resolver.resolve(host, port); asio::connect(socket_, endpoints); - log_->info("Connected to {}:{}", host, port); + TLOGI(log_, "Connected to {}:{}", host, port); is_normal_ = true; return true; } catch (const std::exception& ex) { - log_->error("Connection failed: {}", ex.what()); + TLOGE(log_, "Connection failed: {}", ex.what()); return false; } } @@ -28,9 +28,9 @@ void CTcpClient::disconnect() try { socket_.shutdown(asio::ip::tcp::socket::shutdown_both); socket_.close(); - log_->info("Disconnected."); + TLOGI(log_, "Disconnected."); } catch (const std::exception& ex) { - log_->error("Error during disconnection: {}", ex.what()); + TLOGE(log_, "Error during disconnection: {}", ex.what()); } } } @@ -38,15 +38,15 @@ void CTcpClient::disconnect() bool CTcpClient::send(const char* data, int len) { if (!is_normal_) { - log_->error("abnormal state, will not send."); + TLOGE(log_, "abnormal state, will not send."); return false; } try { auto send_size = asio::write(socket_, asio::buffer(data, len)); - // log_->info("Need Send len: {} Real Send len: {}", len, send_size); + // TLOGI(log_, "Need Send len: {} Real Send len: {}", len, send_size); return static_cast(send_size) == len; } catch (const std::exception& ex) { - log_->error("Send failed: {}", ex.what()); + TLOGE(log_, "Send failed: {}", ex.what()); return false; } } @@ -67,10 +67,10 @@ void CTcpClient::async_recv() return; } if (ec.value() == 125) { - log_->info("{} exit.", __FUNCTION__); + TLOGI(log_, "{} exit.", __FUNCTION__); return; } - log_->error("{} {} error => {}", __FUNCTION__, ec.value(), ec.message()); + TLOGE(log_, "{} {} error => {}", __FUNCTION__, ec.value(), ec.message()); } else { buffer_.push(tmp_buf_.data(), length); while (true) { diff --git a/server/main.cpp b/server/main.cpp index 42bbf3a..d8d3714 100644 --- a/server/main.cpp +++ b/server/main.cpp @@ -24,15 +24,15 @@ int main(int argc, char* argv[]) SetConsoleMode(hConsole, mode); #endif - g_Logger->info("Build At {} {} under {} on {}", __DATE__, __TIME__, VERSION_GIT_COMMIT, - VERSION_GIT_BRANCH); + TLOGI(g_Logger, "Build At {} {} under {} on {}", __DATE__, __TIME__, VERSION_GIT_COMMIT, + VERSION_GIT_BRANCH); int port = 9898; if (argc < 2) { - g_Logger->info("Use Default Port:{}", port); + TLOGI(g_Logger, "Use Default Port:{}", port); } else { std::string str_port(argv[1]); port = std::stoi(str_port); - g_Logger->info("Use Port:{}", port); + TLOGI(g_Logger, "Use Port:{}", port); } asio::io_context io_context; CTcpServer server(io_context, g_Logger); diff --git a/server/server.cpp b/server/server.cpp index 92f5d24..1f23f4d 100644 --- a/server/server.cpp +++ b/server/server.cpp @@ -26,23 +26,23 @@ bool CTcpServer::start(unsigned short port) { asio::ip::tcp::resolver resolver(io_context_); asio::ip::tcp::resolver::query query(asio::ip::host_name(), ""); - log_->info("version: {}", VERSION_NUM); - log_->info("opensource: {}", VERSION_URL); + TLOGI(log_, "version: {}", VERSION_NUM); + TLOGI(log_, "opensource: {}", VERSION_URL); try { auto it = resolver.resolve(query); - log_->debug("Here are the local IP addresses you may use."); - log_->debug("==========================================="); + TLOGD(log_, "Here are the local IP addresses you may use."); + TLOGD(log_, "==========================================="); int i = 1; while (!it.empty()) { asio::ip::address addr = it->endpoint().address(); - log_->info("({}){}", i, addr.to_string()); + TLOGI(log_, "({}){}", i, addr.to_string()); ++it; ++i; } - log_->debug("==========================================="); + TLOGD(log_, "==========================================="); } catch (const std::exception& e) { - log_->warn("{}", e.what()); - log_->info("will not show local IP."); + TLOGW(log_, "{}", e.what()); + TLOGI(log_, "will not show local IP."); } asio::ip::tcp::endpoint endpoint(asio::ip::tcp::v4(), port); @@ -52,14 +52,14 @@ bool CTcpServer::start(unsigned short port) acceptor_.bind(endpoint); acceptor_.listen(); } catch (const asio::system_error& e) { - log_->error("Failed to bind to {}: {}", endpoint.address().to_string(), e.what()); + TLOGE(log_, "Failed to bind to {}: {}", endpoint.address().to_string(), e.what()); return false; } auto bound_endpoint = acceptor_.local_endpoint(); server_ip_ = bound_endpoint.address().to_string() + ":" + std::to_string(bound_endpoint.port()); accept_client(); th_monitor_idle_ = std::thread([this]() { monitor_idle(); }); - log_->info("Server started on port {}", port); + TLOGI(log_, "Server started on port {}", port); return true; } @@ -127,10 +127,10 @@ void CTcpServer::trans_data(CFrameBuffer* buf) switch (buf->type_) { case TYPE_GET_LIST: { - log_->info("[{}] GetList.", buf->fid_); + TLOGI(log_, "[{}] GetList.", buf->fid_); get_client_list(&buf); if (fcli && !send_frame(fcli->socket_, buf)) { - log_->error("GetList send failed."); + TLOGE(log_, "GetList send failed."); } break; } @@ -143,7 +143,7 @@ void CTcpServer::trans_data(CFrameBuffer* buf) break; } case TYPE_CANCEL_LIST: { - log_->info("[{}] Cancle Task.", buf->fid_); + TLOGI(log_, "[{}] Cancle Task.", buf->fid_); if (fcli) { fcli->task_.clear(); fcli->task_time_.clear(); @@ -169,7 +169,7 @@ void CTcpServer::trans_data(CFrameBuffer* buf) } default: if (check_double(buf, fcli, tcli) && tcli && !send_frame(tcli->socket_, buf)) { - log_->error("Send from {} to {} failed Or One Offline.", buf->fid_, buf->tid_); + TLOGE(log_, "Send from {} to {} failed Or One Offline.", buf->fid_, buf->tid_); } break; } @@ -187,19 +187,19 @@ bool CTcpServer::check_double(CFrameBuffer* buf, std::shared_ptr& f } if (fcli == nullptr && tcli) { buf->type_ = TYPE_OFFLINE; - log_->warn("A Notic {} That {} Offline.", buf->tid_, buf->fid_); + TLOGW(log_, "A Notic {} That {} Offline.", buf->tid_, buf->fid_); send_frame(tcli->socket_, buf); return false; } if (tcli == nullptr && fcli) { std::swap(buf->fid_, buf->tid_); buf->type_ = TYPE_OFFLINE; - log_->warn("B Notic {} That {} Offline.", buf->tid_, buf->fid_); + TLOGW(log_, "B Notic {} That {} Offline.", buf->tid_, buf->fid_); send_frame(fcli->socket_, buf); return false; } if (tcli == nullptr && fcli == nullptr) { - log_->warn("Both Offline.", buf->fid_, buf->tid_); + TLOGW(log_, "Both Offline.", buf->fid_, buf->tid_); return false; } return true; @@ -217,10 +217,10 @@ void CTcpServer::accept_client() { std::unique_lock lock(cli_mut_); if (client_map_.size() >= 100) { - log_->info("Max client connections reached. Closing connection from {}", client_key); + TLOGI(log_, "Max client connections reached. Closing connection from {}", client_key); socket->close(); } else { - log_->info("New connection from {}", client_key); + TLOGI(log_, "New connection from {}", client_key); auto cache = std::make_shared(); cache->socket_ = socket; cache->online_time_ = OfUtil::now_time(); @@ -250,7 +250,7 @@ void CTcpServer::th_client(const std::shared_ptr& socket, client_threads_.at(client_key).detach(); client_threads_.erase(client_key); } - log_->warn("th_client deleter client {} exit.", client_key); + TLOGW(log_, "th_client deleter client {} exit.", client_key); }); try { @@ -259,7 +259,7 @@ void CTcpServer::th_client(const std::shared_ptr& socket, { std::shared_lock lock(cli_mut_); if (!client_map_.count(client_key)) { - log_->error("Not Find Client{} in cache.", client_key); + TLOGE(log_, "Not Find Client{} in cache.", client_key); return; } cache = client_map_[client_key]; @@ -297,7 +297,7 @@ void CTcpServer::th_client(const std::shared_ptr& socket, } } } catch (std::exception& e) { - log_->error("Error with client {}: {}", client_key, e.what()); + TLOGE(log_, "Error with client {}: {}", client_key, e.what()); } } @@ -310,19 +310,19 @@ bool CTcpServer::send_frame(const std::shared_ptr& socket } if (!CTransProtocal::pack(buf, &out_buf, out_len)) { - log_->error("{} pack failed.", __FUNCTION__); + TLOGE(log_, "{} pack failed.", __FUNCTION__); return false; } try { if (!socket->send(asio::buffer(out_buf, out_len))) { - log_->error("{} send failed, buf type:{}, fid:{}, tid:{}", __FUNCTION__, - static_cast(buf->type_), buf->fid_, buf->tid_); + TLOGE(log_, "{} send failed, buf type:{}, fid:{}, tid:{}", __FUNCTION__, + static_cast(buf->type_), buf->fid_, buf->tid_); delete[] out_buf; return false; } } catch (const std::exception& e) { - log_->error("send failed, type:{}, fid:{}, tid:{}, mark:{}", static_cast(buf->type_), buf->fid_, - buf->tid_, buf->mark_); + TLOGE(log_, "send failed, type:{}, fid:{}, tid:{}, mark:{}", static_cast(buf->type_), buf->fid_, + buf->tid_, buf->mark_); } delete[] out_buf; @@ -344,7 +344,7 @@ void CTcpServer::monitor_idle() std::chrono::duration_cast(now - item.second->last_active_time_) .count(); if (duration >= remove_after_time) { - log_->warn("OnLine Time [{}] sec, Proactively disconnect:{}", duration, item.first); + TLOGW(log_, "OnLine Time [{}] sec, Proactively disconnect:{}", duration, item.first); remove_vec.push_back(item.first); item.second->socket_->shutdown(asio::ip::tcp::socket::shutdown_both); item.second->socket_->close(); diff --git a/util/util.h b/util/util.h index 02fd66b..f3f15f7 100644 --- a/util/util.h +++ b/util/util.h @@ -91,4 +91,32 @@ inline std::string now_str() << std::setw(3) << milliseconds.count() << "] "; return timestamp.str(); +} + +template void TLOGI(const Log_t& logger, const std::string& format, Args&&... args) +{ + fc_lock_print(); + logger->info(format, std::forward(args)...); + fc_unlock_print(); +} + +template void TLOGW(const Log_t& logger, const std::string& format, Args&&... args) +{ + fc_lock_print(); + logger->warn(format, std::forward(args)...); + fc_unlock_print(); +} + +template void TLOGE(const Log_t& logger, const std::string& format, Args&&... args) +{ + fc_lock_print(); + logger->error(format, std::forward(args)...); + fc_unlock_print(); +} + +template void TLOGD(const Log_t& logger, const std::string& format, Args&&... args) +{ + fc_lock_print(); + logger->debug(format, std::forward(args)...); + fc_unlock_print(); } \ No newline at end of file