#include "log_util.h" #include #include #include #include #include #include "referer.h" ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // class�� log_cls* log_cls::inst_ = nullptr; log_cls::log_cls(const char* path_file, log_level level, int32_t max_size) : file_(path_file), max_size_(max_size), level_(level), dst_(nullptr) { create_log_file(); } log_cls::~log_cls() { if (dst_) fclose(dst_); } void log_cls::create_log_file(void) { dst_ = fopen(file_.c_str(), "a+b"); if (dst_) { fseek(dst_, 0, SEEK_END); if (ftell(dst_) == 0) { unsigned char bom[] = { 0x0ef, 0x0bb, 0x0bf }; fwrite(bom, sizeof(bom), 1, dst_); } else fwrite("\n\n\n", 1, 3, dst_); } else printf("# Failed to create log file(%s): %d(%s)\n", file_.c_str(), errno, strerror(errno)); } void log_cls::log_internal(const char* txt) { std::string now("[" + chronograph::now() + "] "); now += txt; { LOCKER locker(lock_); if (dst_) { size_t wrote = fwrite(now.c_str(), 1, now.length(), dst_); if(wrote != now.length()) printf("# Write log failed: %d(%s)\n", errno, strerror(errno)); fflush(dst_); if (ftell(dst_) >= max_size_) { fclose(dst_); remove(file_.c_str()); create_log_file(); } } } } void log_cls::initialize(const char* path_file, log_level level, int32_t max_size) { if (log_cls::inst_) delete log_cls::inst_; std::string path(""); if (!path_file || *path_file == 0) { size_t pos = 0; std::string def_dir(getenv("HOME") + std::string("/.scanner/log")); path = sys_util::get_module_path(); pos = path.rfind('/'); if (pos++ != std::string::npos) path.erase(0, pos); path.insert(0, def_dir + "/"); sys_util::create_folder(def_dir.c_str()); path += ".log"; path_file = path.c_str(); } log_cls::inst_ = new log_cls(path_file, level, max_size); } int32_t log_cls::log_when_err(int32_t err, const char* oper_desc, log_level level) { if(err == -1) { err = errno; log_cls::log(level, "%s = %s\n", oper_desc, strerror(err)); } return err; } log_level log_cls::get_log_level(void) { if (log_cls::inst_) return log_cls::inst_->level_; else return LOG_LEVEL_ALL; } std::string log_cls::get_log_file(void) { if (log_cls::inst_) return log_cls::inst_->file_; else return ""; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //