diff --git a/.vscode/settings.json b/.vscode/settings.json index 8660918..84c40f6 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -143,7 +143,9 @@ "semaphore": "cpp", "span": "cpp", "text_encoding": "cpp", - "*.in": "cpp" + "*.in": "cpp", + "hash_map": "cpp", + "stdfloat": "cpp" }, "makefile.configureOnOpen": false, "C_Cpp.default.configurationProvider": "ms-vscode.cmake-tools" diff --git a/CMakeLists.txt b/CMakeLists.txt index 6ef535b..49af37f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -28,6 +28,7 @@ set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/bin/${CMAKE_BUILD_TYPE}/ ) +add_definitions(-DFMT_HEADER_ONLY) include_directories(3rd) include_directories(.) include_directories(${PROJECT_BINARY_DIR}) diff --git a/client/client.cpp b/client/client.cpp index 6da440e..9d2f75e 100644 --- a/client/client.cpp +++ b/client/client.cpp @@ -13,9 +13,9 @@ namespace fs = boost::filesystem; namespace fs = std::filesystem; #endif -CClient::CClient(const std::shared_ptr& logger) : logger_(logger) +CClient::CClient() { - client_ = std::make_shared(io_context_, logger_); + client_ = std::make_shared(io_context_); supported_.push_back("Get"); sleep_.set_timeout(5000); } @@ -52,7 +52,7 @@ void CClient::run(const std::string& ip, const std::string& port) { th_run_ = true; if (!client_->connect(ip, port)) { - logger_->info("{} connect err.", __FUNCTION__); + pinfo("{} connect err.", __FUNCTION__); return; } client_->register_func([&](CFrameBuffer* buf) { handle_frame(buf); }); @@ -65,7 +65,7 @@ void CClient::run(const std::string& ip, const std::string& port) send_frame(bf); delete bf; - logger_->warn("SupportCmd:Get|Up|Down|Cancel|Update"); + pwarn("SupportCmd:Get|Up|Down|Cancel|Update"); fc_append('|'); while (1) { @@ -74,7 +74,7 @@ void CClient::run(const std::string& ip, const std::string& port) break; } if (!th_run_ || !client_->is_normal()) { - logger_->warn("The link has been closed and cannot be continued. It will automatically exit."); + pwarn("The link has been closed and cannot be continued. It will automatically exit."); break; } std::string cmd_input(readline); @@ -96,7 +96,7 @@ void CClient::run(const std::string& ip, const std::string& port) } auto vec = COfStr::split(cmd_input, " "); if (vec.size() < 2) { - logger_->error("No matched cmd, May be param size incorrect."); + perror("No matched cmd, May be param size incorrect."); continue; } std::string param(cmd_input); @@ -115,11 +115,11 @@ void CClient::run(const std::string& ip, const std::string& port) up_task(param); continue; } - logger_->error("No matched cmd, May be param size incorrect."); + perror("No matched cmd, May be param size incorrect."); } client_->disconnect(); thread.join(); - logger_->info("{} exit.", __FUNCTION__); + pinfo("{} exit.", __FUNCTION__); } bool CClient::get_task_list() @@ -132,17 +132,17 @@ bool CClient::get_task_list() bool CClient::down_task(const std::string& param) { if (downloading_) { - logger_->warn("Have Task Downloading, Please wait....."); + pwarn("Have Task Downloading, Please wait....."); return false; } int id = std::stoi(param); if (!task_list_.count(id)) { - logger_->error("No matched id[{}] in task list.", id); + perror("No matched id[{}] in task list.", id); return false; } if (task_list_[id]->id == own_id_) { - logger_->warn("You can't down your own file!!!"); + pwarn("You can't down your own file!!!"); return false; } @@ -150,7 +150,7 @@ bool CClient::down_task(const std::string& param) down_ = std::make_shared(); if (vec.empty()) { - logger_->warn("No files List, Please Check!"); + pwarn("No files List, Please Check!"); return false; } @@ -171,7 +171,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) { - logger_->warn("Have Task Upping, Please wait!"); + pwarn("Have Task Upping, Please wait!"); return false; } } @@ -182,12 +182,12 @@ bool CClient::up_task(const std::string& param) for (const auto& item : list) { if (!fs::exists(item)) { - logger_->error("File {} not exist, please check.", item); + perror("File {} not exist, please check.", item); return false; } if (!fs::is_regular_file(item)) { - logger_->error("Only Support Up File, But directory.", item); + perror("Only Support Up File, But directory.", item); return false; } @@ -198,7 +198,7 @@ bool CClient::up_task(const std::string& param) } } if (msg.empty()) { - logger_->warn("{} msg empty.", __FUNCTION__); + pwarn("{} msg empty.", __FUNCTION__); return false; } @@ -220,7 +220,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) { - logger_->warn("Have Task Upping, Please wait!"); + pwarn("Have Task Upping, Please wait!"); return false; } } @@ -247,10 +247,10 @@ bool CClient::down_one_file(const std::string& id, const std::string& file, cons down_->cur_file_ = fs::path(local_dir).append(remote_file.filename().string()).string(); } - logger_->warn("Start Down => {} To {}", down_->cur_remote_file_, down_->cur_file_); + pwarn("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()) { - logger_->error("Open {} Failed.", down_->cur_file_); + perror("Open {} Failed.", down_->cur_file_); return false; } @@ -261,7 +261,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())) { - logger_->error("{} request open file [{}] send failed.", __FUNCTION__, down_->cur_remote_file_); + perror("{} request open file [{}] send failed.", __FUNCTION__, down_->cur_remote_file_); down_->cur_remote_id_.clear(); down_->cur_remote_file_.clear(); return false; @@ -277,7 +277,7 @@ bool CClient::down_one_file(const std::string& id, const std::string& file, cons CTransProtocal::display_progress(percent); } if (!th_run_) { - logger_->error("Interrup When Receive File."); + perror("Interrup When Receive File."); report_trans_ret(TRANS_FAILED); return false; } @@ -287,12 +287,10 @@ bool CClient::down_one_file(const std::string& id, const std::string& file, cons CTransProtocal::display_progress(percent); } if (cur_file_size_ == cur_down_size_) { - logger_->warn("Trans done, close file {}, total:[{}/{}]", down_->cur_file_, cur_down_size_, - cur_file_size_); + pwarn("Trans done, close file {}, total:[{}/{}]", down_->cur_file_, cur_down_size_, cur_file_size_); return true; } else { - logger_->warn("Trans failed, close file {}, total:[{}/{}]", down_->cur_file_, cur_down_size_, - cur_file_size_); + pwarn("Trans failed, close file {}, total:[{}/{}]", down_->cur_file_, cur_down_size_, cur_file_size_); return false; } } @@ -337,31 +335,31 @@ bool CClient::request_update_list(const std::string& param) { auto tvec = COfStr::split(param, " "); if (tvec.size() < 2) { - logger_->error("{} invalid param format [{}]", __FUNCTION__, param); + perror("{} invalid param format [{}]", __FUNCTION__, param); return false; } int index = std::stoi(tvec[0]); std::string list_file = tvec[1]; if (downloading_) { - logger_->warn("Have Task Downloading, Please wait....."); + pwarn("Have Task Downloading, Please wait....."); return false; } if (!task_list_.count(index)) { - logger_->error("No Index Found {}.", index); + perror("No Index Found {}.", index); return false; } const auto& sr = task_list_[index]; if (sr->id == own_id_) { - logger_->warn("You can't update your own file!!!"); + pwarn("You can't update your own file!!!"); return false; } // 读取list文件 std::ifstream in(COfPath::to_full(list_file)); if (!in.is_open()) { - logger_->error("Can't Open File:{}", COfPath::to_full(list_file)); + perror("Can't Open File:{}", COfPath::to_full(list_file)); return false; } std::istreambuf_iterator iterf(in); @@ -378,11 +376,11 @@ bool CClient::request_update_list(const std::string& param) if (hitem.empty()) { continue; } - logger_->info("---> check {}", hitem); + pinfo("---> check {}", hitem); auto v = COfStr::split(hitem, "|"); if (v.size() >= 2) { if (!fs::exists(v[0])) { - logger_->error("file {} not exist.", v[0]); + perror("file {} not exist.", v[0]); valid = false; break; } @@ -394,7 +392,7 @@ bool CClient::request_update_list(const std::string& param) } if (!valid) { - logger_->error("Judge List File {} Format Not Passed.", list_file); + perror("Judge List File {} Format Not Passed.", list_file); return false; } @@ -406,7 +404,7 @@ bool CClient::request_update_list(const std::string& param) buf->tid_ = task_list_[index]->id; if (!send_frame(buf.get())) { - logger_->error("Send Failed {}", __LINE__); + perror("Send Failed {}", __LINE__); return false; } return true; @@ -422,13 +420,13 @@ bool CClient::check_update_list(const std::string& content, std::maperror("Size not 2 {}", item); + perror("Size not 2 {}", item); valid = true; break; } if (!fs::exists(vi[1])) { valid = false; - logger_->error("Not exist {}", vi[1]); + perror("Not exist {}", vi[1]); break; } files[vi[0]] = vi[1]; @@ -450,10 +448,10 @@ bool CClient::down_update_file(std::map files) } if (suc) { buf->type_ = TYPE_DONE_UPDATE_LIST; - logger_->info("Do Task From {} Done!", buf->tid_); + pinfo("Do Task From {} Done!", buf->tid_); } else { buf->type_ = TYPE_FAILED_UPDATE_LIST; - logger_->info("Do Task From {} Failed!", buf->tid_); + pinfo("Do Task From {} Failed!", buf->tid_); } send_frame(buf.get()); return suc; @@ -464,7 +462,7 @@ bool CClient::send_frame(CFrameBuffer* buf) char* out_buf{}; int out_len{}; if (!CTransProtocal::pack(buf, &out_buf, out_len)) { - logger_->error("{} pack failed.", __FUNCTION__); + perror("{} pack failed.", __FUNCTION__); return false; } std::lock_guard lock(send_mut_); @@ -479,12 +477,12 @@ bool CClient::send_frame(CFrameBuffer* buf) void CClient::handle_frame(CFrameBuffer* buf) { if (buf == nullptr) { - logger_->error("{} nullptr.", __FUNCTION__); + perror("{} nullptr.", __FUNCTION__); return; } switch (buf->type_) { case TYPE_GET_ID: { - logger_->debug("Your ID:{}", buf->tid_); + pdebug("Your ID:{}", buf->tid_); own_id_ = buf->tid_; break; } @@ -500,9 +498,9 @@ void CClient::handle_frame(CFrameBuffer* buf) } if (real.find("[") == std::string::npos) { #ifdef _WIN32 - logger_->info("FILE ==> {}", CCodec::u8_to_ansi(real)); + pinfo("FILE ==> {}", CCodec::u8_to_ansi(real)); #else - logger_->info("FILE ==> {}", real); + pinfo("FILE ==> {}", real); #endif task_list_[index]->files.push_back(real); } else { @@ -522,8 +520,8 @@ void CClient::handle_frame(CFrameBuffer* buf) task_list_[index]->id = id; } - logger_->debug("*****************************************"); - logger_->info("{}", real); + pdebug("*****************************************"); + pinfo("{}", real); } } break; @@ -538,7 +536,7 @@ void CClient::handle_frame(CFrameBuffer* buf) down_->file_.write(buf->data_, buf->len_); if (down_->file_.fail()) { report_trans_ret(TRANS_FAILED); - logger_->warn("no matched write and data. {}", buf->len_); + pwarn("no matched write and data. {}", buf->len_); } cur_down_size_ += buf->len_; } @@ -557,7 +555,7 @@ 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()) { - logger_->error("Ready Send File {} Open Failed.", up_[buf->fid_]->cur_file_); + perror("Ready Send File {} Open Failed.", up_[buf->fid_]->cur_file_); break; } keys = buf->fid_; @@ -575,7 +573,7 @@ void CClient::handle_frame(CFrameBuffer* buf) if (buf->mark_) { std::lock_guard lock(mutex_); if (!up_.count(buf->fid_)) { - logger_->warn("Offline no match."); + pwarn("Offline no match."); break; } auto t = up_[buf->fid_]; @@ -583,7 +581,7 @@ void CClient::handle_frame(CFrameBuffer* buf) break; } if (downloading_ && !down_->cur_remote_file_.empty()) { - logger_->warn("Stop Down {} From {}.", down_->cur_remote_file_, buf->fid_); + pwarn("Stop Down {} From {}.", down_->cur_remote_file_, buf->fid_); } report_trans_ret(TRANS_FAILED); break; @@ -599,14 +597,14 @@ void CClient::handle_frame(CFrameBuffer* buf) } std::swap(buf->tid_, buf->fid_); if (!send_frame(buf)) { - logger_->error("Send Failed {}.", __LINE__); + perror("Send Failed {}.", __LINE__); break; } if (buf->type_ == TYPE_UNCONFIRM_UPDATE_LIST) { break; } list_serve_id_ = buf->tid_; - logger_->debug("Do Task From {}.", buf->tid_); + pdebug("Do Task From {}.", buf->tid_); if (update_list_th_.joinable()) { update_list_th_.join(); } @@ -614,26 +612,26 @@ void CClient::handle_frame(CFrameBuffer* buf) break; } case TYPE_CONFIRM_UPDATE_LIST: { - logger_->info("remote {} check {} passed!", buf->fid_, list_file_); + pinfo("remote {} check {} passed!", buf->fid_, list_file_); break; } case TYPE_UNCONFIRM_UPDATE_LIST: { - logger_->error("remote {} check {} not passed!", buf->fid_, list_file_); + perror("remote {} check {} not passed!", buf->fid_, list_file_); break; } case TYPE_DONE_UPDATE_LIST: { - logger_->info("remote {} do task {} success!", buf->fid_, list_file_); + pinfo("remote {} do task {} success!", buf->fid_, list_file_); break; } case TYPE_FAILED_UPDATE_LIST: { - logger_->info("remote {} do task {} failed!", buf->fid_, list_file_); + pinfo("remote {} do task {} failed!", buf->fid_, list_file_); break; } case TYPE_FILE_SIZE: { std::string str_size(buf->data_, buf->len_); long long size = std::stoll(str_size); std::string show_str = OfUtil::get_file_size(size); - logger_->info("Ready Down Size: {}", show_str); + pinfo("Ready Down Size: {}", show_str); cur_file_size_ = size; } default: @@ -649,13 +647,13 @@ void CClient::send_file_data_th(const char* keys) { std::lock_guard lock(mutex_); if (!up_.count(str_key)) { - logger_->error("{} no matched key.", __FUNCTION__); + perror("{} no matched key.", __FUNCTION__); return; } t = up_[str_key]; } - logger_->info("Start Trans File {} To {}", t->cur_file_, str_key); + pinfo("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; @@ -667,11 +665,11 @@ void CClient::send_file_data_th(const char* keys) buf->type_ = TYPE_FILE_SIZE; std::string str_size = std::to_string(size); - logger_->info("To {} File Size: {} [{}]", str_key, ofen::OfUtil::get_file_size(size), size); + pinfo("To {} File Size: {} [{}]", str_key, ofen::OfUtil::get_file_size(size), size); buf->len_ = std::snprintf(buf->data_, g_BuffSize, "%s", str_size.c_str()); if (!send_frame(buf.get())) { report_trans_ret(TRANS_FAILED, str_key); - logger_->error("Stop Trans {} To {} failed.", t->cur_file_, str_key); + perror("Stop Trans {} To {} failed.", t->cur_file_, str_key); return; } buf->type_ = TYPE_TRANS_FILE; @@ -679,7 +677,7 @@ void CClient::send_file_data_th(const char* keys) while (!t->file_.eof()) { if (t->trans_state_ == TRANS_BREAK) { - logger_->warn("Stop Trans {} To {} failed.", t->cur_file_, str_key); + pwarn("Stop Trans {} To {} failed.", t->cur_file_, str_key); report_trans_ret(TRANS_FAILED, str_key); return; } @@ -687,7 +685,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); - logger_->error("Stop Trans {} To {} failed.", t->cur_file_, str_key); + perror("Stop Trans {} To {} failed.", t->cur_file_, str_key); return; } // std::this_thread::sleep_for(std::chrono::milliseconds(10)); @@ -695,10 +693,10 @@ void CClient::send_file_data_th(const char* keys) buf->type_ = TYPE_TRANS_DONE; if (!send_frame(buf.get())) { - logger_->error("send_file_data_th send DONE failed."); + perror("send_file_data_th send DONE failed."); } report_trans_ret(TRANS_DONE, str_key); - logger_->debug("Trans File {} To {} Done !!!", t->cur_file_, str_key); + pdebug("Trans File {} To {} Done !!!", t->cur_file_, str_key); } void CClient::hearts() @@ -708,7 +706,7 @@ void CClient::hearts() while (th_run_) { sleep_.sleep(); if (th_run_ && !send_frame(buf.get())) { - logger_->error("{} send failed.", __FUNCTION__); + perror("{} send failed.", __FUNCTION__); th_run_ = false; } } diff --git a/client/client.h b/client/client.h index ed4c3d6..26fa962 100644 --- a/client/client.h +++ b/client/client.h @@ -1,4 +1,5 @@ #pragma once +#include #include #include #include @@ -7,7 +8,6 @@ #include #include #include -#include using namespace ofen; struct DownClientInfo { @@ -35,7 +35,7 @@ constexpr int down_check_wait = 100; // millsec class CClient { public: - CClient(const std::shared_ptr& logger); + CClient(); ~CClient(); public: diff --git a/client/config.cpp b/client/config.cpp index 50f104f..98ff977 100644 --- a/client/config.cpp +++ b/client/config.cpp @@ -9,7 +9,7 @@ namespace fs = boost::filesystem; namespace fs = std::filesystem; #endif -CServerConfig::CServerConfig(std::shared_ptr& logger) : logger_(logger) +CServerConfig::CServerConfig() { } @@ -26,7 +26,7 @@ bool CServerConfig::baseInit() } SI_Error ret = ini_handle_.LoadFile(config_path_.c_str()); if (ret != SI_OK) { - logger_->error("Load Ini [{}] Failed.", config_path_); + perror("Load Ini [{}] Failed.", config_path_); return false; } init_ = true; @@ -38,7 +38,7 @@ bool CServerConfig::read_ini(std::vector& set) assert(init_ == true); long groups = ini_handle_.GetLongValue("BASE", "GROUPS"); if (groups < 1) { - logger_->error("GROUPS num < 1."); + perror("GROUPS num < 1."); return false; } set.clear(); @@ -85,9 +85,9 @@ bool CServerConfig::remove_ini(long num) if (!read_ini(set)) { return false; } - set.erase(std::remove_if(set.begin(), set.end(), - [&num](const TransmSet& item) { return item.grp_id == num; }), - set.end()); + set.erase( + std::remove_if(set.begin(), set.end(), [&num](const TransmSet& item) { return item.grp_id == num; }), + set.end()); ini_handle_.Reset(); ini_handle_.SetLongValue("BASE", "GROUPS", static_cast(set.size())); return write_ini(set); @@ -108,7 +108,7 @@ bool CServerConfig::get_ini(const std::vector& set, long num, TransmS void CServerConfig::gen_default_ini(const std::string& path) { - logger_->warn("Gen Default Setting Ini in [{}].", path); + pwarn("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/config.h b/client/config.h index bfedfe2..e724ab1 100644 --- a/client/config.h +++ b/client/config.h @@ -23,7 +23,7 @@ struct CmdParam { class CServerConfig { public: - CServerConfig(std::shared_ptr& logger); + CServerConfig(); ~CServerConfig(); public: @@ -41,5 +41,4 @@ private: bool init_{false}; CSimpleIniA ini_handle_{}; std::string config_path_{}; - std::shared_ptr logger_; }; \ No newline at end of file diff --git a/client/main.cpp b/client/main.cpp index e1380fc..7ac05b2 100644 --- a/client/main.cpp +++ b/client/main.cpp @@ -43,7 +43,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); + pinfo("{} => {}:{}", item.group, item.ip, item.port); } return true; } @@ -52,42 +52,40 @@ 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!"); + perror("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!"); + perror("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); + perror("add {}:{} failed.", ip, port); return false; } - g_Logger->info("add {}:{} success.", ip, port); + pinfo("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); + perror("remove config num=[{}] failed, please check!", param.removeValue); return false; } - g_Logger->info("remove config num=[{}] success!", param.removeValue); + pinfo("remove config num=[{}] success!", param.removeValue); return true; } - g_Logger->error("not matched!", param.removeValue); + perror("not matched!", param.removeValue); return false; } int main(int argc, char* argv[]) { - auto log_path = ofen::COfPath::to_full("client.log"); - g_Logger = get_logger("client", log_path); - g_Config = std::make_shared(g_Logger); + g_Config = std::make_shared(); if (!g_Config->baseInit()) { return -1; } @@ -99,7 +97,7 @@ int main(int argc, char* argv[]) return 0; } if (!exec_cmd(param, run)) { - g_Logger->error("exec_cmd failed!"); + perror("exec_cmd failed!"); return -1; } if (!run) { @@ -112,14 +110,13 @@ 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); + perror("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); - CClient client(g_Logger); + pinfo("Build At {} {} under {} on {}", __DATE__, __TIME__, VERSION_GIT_COMMIT, VERSION_GIT_BRANCH); + pinfo("use ip => [{}], port => [{}]", use.ip, use.port); + CClient client; client.run(use.ip, std::to_string(use.port)); - g_Logger->info("exit =========="); + pinfo("exit =========="); return 0; } \ No newline at end of file diff --git a/filecomplete b/filecomplete index 569ba72..909c68c 160000 --- a/filecomplete +++ b/filecomplete @@ -1 +1 @@ -Subproject commit 569ba7232d12573bff572d71043a5fd0e03f9df0 +Subproject commit 909c68cf6e376acb975af21af7709b1129e5d0db diff --git a/net/net_base.cpp b/net/net_base.cpp index 70074af..fc461ee 100644 --- a/net/net_base.cpp +++ b/net/net_base.cpp @@ -1,7 +1,6 @@ #include "net_base.h" -CTcpClient::CTcpClient(asio::io_context& io_context, const std::shared_ptr& logger) - : logger_(logger), io_context_(io_context), socket_(io_context_) +CTcpClient::CTcpClient(asio::io_context& io_context) : io_context_(io_context), socket_(io_context_) { } @@ -15,11 +14,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); - logger_->info("Connected to {}:{}", host, port); + pinfo("Connected to {}:{}", host, port); is_normal_ = true; return true; } catch (const std::exception& ex) { - logger_->error("Connection failed: {}", ex.what()); + perror("Connection failed: {}", ex.what()); return false; } } @@ -30,9 +29,9 @@ void CTcpClient::disconnect() try { socket_.shutdown(asio::ip::tcp::socket::shutdown_both); socket_.close(); - logger_->info("Disconnected."); + pinfo("Disconnected."); } catch (const std::exception& ex) { - logger_->error("Error during disconnection: {}", ex.what()); + perror("Error during disconnection: {}", ex.what()); } } } @@ -40,15 +39,15 @@ void CTcpClient::disconnect() bool CTcpClient::send(const char* data, int len) { if (!is_normal_) { - logger_->error("abnormal state, will not send."); + perror("abnormal state, will not send."); return false; } try { auto send_size = asio::write(socket_, asio::buffer(data, len)); - // logger_->info("Need Send len: {} Real Send len: {}", len, send_size); + // pinfo("Need Send len: {} Real Send len: {}", len, send_size); return static_cast(send_size) == len; } catch (const std::exception& ex) { - logger_->error("Send failed: {}", ex.what()); + perror("Send failed: {}", ex.what()); return false; } } @@ -69,10 +68,10 @@ void CTcpClient::async_recv() return; } if (ec.value() == 125) { - logger_->info("{} exit.", __FUNCTION__); + pinfo("{} exit.", __FUNCTION__); return; } - logger_->error("{} {} error => {}", __FUNCTION__, ec.value(), ec.message()); + perror("{} {} error => {}", __FUNCTION__, ec.value(), ec.message()); } else { buffer_.push(tmp_buf_.data(), length); while (true) { diff --git a/net/net_base.h b/net/net_base.h index 9d262cc..5dbb5ce 100644 --- a/net/net_base.h +++ b/net/net_base.h @@ -9,7 +9,7 @@ using namespace ofen; class CTcpClient : public std::enable_shared_from_this { public: - CTcpClient(asio::io_context& io_context, const std::shared_ptr& logger); + CTcpClient(asio::io_context& io_context); ~CTcpClient(); public: @@ -21,7 +21,6 @@ public: bool is_normal(); private: - std::shared_ptr logger_; asio::io_context& io_context_; asio::ip::tcp::socket socket_; std::mutex mutex_; diff --git a/ofen b/ofen index 7194832..cf634e2 160000 --- a/ofen +++ b/ofen @@ -1 +1 @@ -Subproject commit 71948320b735e33db511f756b5df83ef3ddcf2c7 +Subproject commit cf634e27daf2f4435fc043d372bc5202fe164766 diff --git a/util/util.cpp b/util/util.cpp index 2094bf8..1251db8 100644 --- a/util/util.cpp +++ b/util/util.cpp @@ -1,7 +1,7 @@ #include "util.h" #include -#include #include +#include std::shared_ptr get_logger(const std::string& mark, const std::string& log_file) { @@ -134,7 +134,7 @@ void CTransProtocal::display_progress(float percent) } } // \r 回到行首 - std::cout << "] " << int(percent * 100.0f) << " %\r"; + std::cout << "] " << int(percent * 100.0f) << " %\r"; std::cout.flush(); } diff --git a/util/util.h b/util/util.h index 6bcc6a9..5704f4b 100644 --- a/util/util.h +++ b/util/util.h @@ -1,7 +1,11 @@ #pragma once #include "of_util.h" +#include #include #include +#include +#include +#include #include #include #include @@ -74,3 +78,33 @@ public: static bool pack(CFrameBuffer* buf, char** out_buf, int& len); static void display_progress(float percent); }; + +inline std::string now_str() +{ + auto now = std::chrono::system_clock::now(); + auto time_t_now = std::chrono::system_clock::to_time_t(now); + auto milliseconds = std::chrono::duration_cast(now.time_since_epoch()) % 1000; + + std::ostringstream timestamp; + timestamp << std::put_time(std::localtime(&time_t_now), "[%Y-%m-%d %H:%M:%S") << "." << std::setfill('0') + << std::setw(3) << milliseconds.count() << "] "; + + return timestamp.str(); +} + +template void pdebug(const std::string& format, Args&&... args) +{ + fmt::print(fg(fmt::color::steel_blue), now_str() + format + "\n", std::forward(args)...); +} +template void pinfo(const std::string& format, Args&&... args) +{ + fmt::print(fg(fmt::color::gray), now_str() + format + "\n", std::forward(args)...); +} +template void pwarn(const std::string& format, Args&&... args) +{ + fmt::print(fg(fmt::color::yellow_green), now_str() + format + "\n", std::forward(args)...); +} +template void perror(const std::string& format, Args&&... args) +{ + fmt::print(fg(fmt::color::orange_red), now_str() + format + "\n", std::forward(args)...); +} \ No newline at end of file