瀏覽代碼

refactor & feat: Log系统改造

SongZihuan 3 年之前
父節點
當前提交
d1aac57ca5

+ 1 - 0
include/core/init.h

@@ -6,6 +6,7 @@
 namespace aFuncore {
     struct InitInfo {
         const std::string &base_dir;
+        aFuntool::LogFactory &factor;
         bool log_asyn;
         aFuntool::LogLevel level;
     };

+ 9 - 9
include/tool/dlc.h

@@ -37,12 +37,12 @@ namespace aFuntool {
     class AFUN_TOOL_EXPORT DlcHandle {
     public:
         DlcHandle(const char *file, int mode) noexcept;  // 仅 openLibary 可用
-        DlcHandle(const DlcHandle &dlc_handle) noexcept;
-        DlcHandle(DlcHandle &&dlc_handle) noexcept;
-        ~DlcHandle() noexcept;
-        DlcHandle &operator=(const DlcHandle &dlc_handle) noexcept;
+        inline DlcHandle(const DlcHandle &dlc_handle) noexcept;
+        inline DlcHandle(DlcHandle &&dlc_handle) noexcept;
+        inline ~DlcHandle() noexcept;
+        inline DlcHandle &operator=(const DlcHandle &dlc_handle) noexcept;
 
-        [[nodiscard]] bool isOpen() const;
+        [[nodiscard]] inline bool isOpen() const;
 
         /**
          * 获得动态库中指定名字的符号
@@ -56,9 +56,9 @@ namespace aFuntool {
         /**
          * 关闭动态库句柄
          */
-        void close();
-        int operator++(int);
-        int operator--(int);
+        inline void close();
+        inline int operator++(int);
+        inline int operator--(int);
 
         AFUN_TOOL_EXPORT static void dlcExit();
 
@@ -70,7 +70,7 @@ namespace aFuntool {
             Handle &operator=(const Handle *dlc) = delete;
             ~Handle();
 
-            [[nodiscard]] bool isOpen() const;
+            [[nodiscard]] inline bool isOpen() const;
 
             /**
              * 获得动态库中指定名字的符号

+ 6 - 6
include/tool/exception.h

@@ -6,23 +6,23 @@ namespace aFuntool {
     class FileOpenException : public std::exception {
         std::string message;
     public:
-        explicit FileOpenException(ConstFilePath file);
-        virtual const char *what();
+        inline explicit FileOpenException(ConstFilePath file);
+        inline virtual const char *what();
     };
 
     class RegexException : public std::exception
     {
         std::string message;
     public:
-        explicit RegexException(const std::string &msg);
-        virtual const char *what();
+        inline explicit RegexException(const std::string &msg);
+        inline virtual const char *what();
     };
 
     class LogFatalError : public std::exception {
         std::string message;
     public:
-        explicit LogFatalError(const char *msg);
-        virtual const char *what();
+        inline explicit LogFatalError(const char *msg);
+        inline virtual const char *what();
     };
 }
 

+ 3 - 3
include/tool/log-m.h → include/tool/log-macro.h

@@ -1,5 +1,5 @@
-#ifndef AFUN_LOG_M_H
-#define AFUN_LOG_M_H
+#ifndef AFUN_LOG_MACRO_H
+#define AFUN_LOG_MACRO_H
 
 #if (defined aFunOFFAllLog || defined aFunOFFLog)
 
@@ -144,4 +144,4 @@
 #define aFunConsoleFatalError 1
 #endif
 
-#endif //AFUN_LOG_M_H
+#endif //AFUN_LOG_MACRO_H

+ 33 - 31
include/tool/log.h

@@ -28,12 +28,10 @@ namespace aFuntool {
     class AFUN_TOOL_EXPORT LogFactory;
 
     class AFUN_TOOL_EXPORT Logger {
-        const std::string id;
-        LogLevel level = log_debug;
-        bool exit = true;
         friend class LogFactory;
     public:
-        explicit Logger(const std::string &id_, LogLevel level_ = log_warning, bool exit_ = true);
+        inline explicit Logger(LogFactory &factor, std::string id, LogLevel level = log_warning, bool exit = true) noexcept;
+
         int writeTrackLog(const char *file, int line, const char *func, const char *format, ...);
         int writeDebugLog(const char *file, int line, const char *func, const char *format, ...);
         int writeInfoLog(const char *file, int line, const char *func, const char *format, ...);
@@ -41,31 +39,22 @@ namespace aFuntool {
         int writeErrorLog(const char *file, int line, const char *func, const char *format, ...);
         int writeSendErrorLog(const char *file, int line, const char *func, const char *format, ...);
         int writeFatalErrorLog(const char *file, int line, const char *func, int exit_code, const char *format, ...);
+    private:
+        const std::string id_;
+        LogLevel level_ = log_debug;
+        bool exit_ = true;
+        LogFactory &factor_;
     };
 
     class AFUN_TOOL_EXPORT LogFactory {
-        bool init;  // 是否已经初始化
-        pid_t pid;
-
-        FILE *log;  // 记录文件输出的位置
-        FILE *csv;
-
-        bool asyn;  // 异步
-        std::thread pt;
-        std::condition_variable cond;  // 有日志
-        std::mutex mutex;
-        struct LogNode *log_buf;
-        struct LogNode **plog_buf;  // 指向 log_buf的末端
-
     public:
-        Logger sys_log = Logger("SYSTEM");
+        Logger sys_log = Logger(*this, "SYSTEM");
         LogFactory();
         ~LogFactory();
         LogFactory(const LogFactory &)=delete;
         LogFactory &operator=(const LogFactory &)=delete;
 
         int initLogSystem(ConstFilePath path, bool is_asyn = true);
-        bool destruct();
         void writeLog(LogLevel level,
                       const char *id, pid_t tid,
                       const char *ti, time_t t,
@@ -88,27 +77,40 @@ namespace aFuntool {
         struct LogNode *pop();
 
         struct ansyData {
-            std::mutex *mutex;
+            LogFactory &factor;
+            std::mutex &mutex;
         };
 
         void ansyWritrLog(ansyData *data);
+    private:
+        bool init_;  // 是否已经初始化
+        pid_t pid_;
+
+        FILE *log_;  // 记录文件输出的位置
+        FILE *csv_;
+
+        bool asyn_;  // 异步
+        std::thread thread_;
+        std::condition_variable cond_;  // 有日志
+        std::mutex mutex_;
+        struct LogNode *log_buf_;
+        struct LogNode **plog_buf_;  // 指向 log_buf的末端
     };
-
-    AFUN_TOOL_EXPORT extern LogFactory log_factory;
 }
 
+#include "log.inline.h"
+
 #ifndef NO_DEFINE_LOG_MACRO
-#include "log-m.h"
-#define getLogger(logger) ((logger) == nullptr ? &aFuntool::log_factory.sys_log : (logger))
+#include "log-macro.h"
 
 #if aFunWriteTrack
-#define trackLog(logger, ...) getLogger(logger)->writeTrackLog(__FILENAME__ , (int)__LINE__, __FUNCTION__, __VA_ARGS__)
+#define trackLog(logger, ...) (logger)->writeTrackLog(__FILENAME__ , (int)__LINE__, __FUNCTION__, __VA_ARGS__)
 #else
 #define trackLog(logger, ...) (nullptr)
 #endif
 
 #if aFunWriteDebug
-#define debugLog(logger, ...) getLogger(logger)->writeDebugLog(__FILENAME__ , (int)__LINE__, __FUNCTION__, __VA_ARGS__)
+#define debugLog(logger, ...) (logger)->writeDebugLog(__FILENAME__ , (int)__LINE__, __FUNCTION__, __VA_ARGS__)
 #define assertDebugLog(c, logger, ...) ((c) || debugLog(logger, "Assert " #c " error : " __VA_ARGS__))
 #else
 #define debugLog(logger, ...) (nullptr)
@@ -116,7 +118,7 @@ namespace aFuntool {
 #endif
 
 #if aFunWriteInfo
-#define infoLog(logger, ...) getLogger(logger)->writeInfoLog(__FILENAME__ , (int)__LINE__, __FUNCTION__, __VA_ARGS__)
+#define infoLog(logger, ...) (logger)->writeInfoLog(__FILENAME__ , (int)__LINE__, __FUNCTION__, __VA_ARGS__)
 #define assertInfoLog(c, logger, ...) ((c) || infoLog(logger, "Assert " #c " error : " __VA_ARGS__))
 #else
 #define infoLog(logger, ...) (nullptr)
@@ -124,7 +126,7 @@ namespace aFuntool {
 #endif
 
 #if !aFunIgnoreWarning
-#define warningLog(logger, ...) getLogger(logger)->writeWarningLog(__FILENAME__ , (int)__LINE__, __FUNCTION__, __VA_ARGS__)
+#define warningLog(logger, ...) (logger)->writeWarningLog(__FILENAME__ , (int)__LINE__, __FUNCTION__, __VA_ARGS__)
 #define assertWarningLog(c, logger, ...) ((c) || warningLog(logger, "Assert " #c " error : " __VA_ARGS__))
 #else
 #define warningLog(logger, ...) (nullptr)
@@ -132,7 +134,7 @@ namespace aFuntool {
 #endif
 
 #if !aFunIgnoreError
-#define errorLog(logger, ...) getLogger(logger)->writeErrorLog(__FILENAME__ , (int)__LINE__, __FUNCTION__, __VA_ARGS__)
+#define errorLog(logger, ...) (logger)->writeErrorLog(__FILENAME__ , (int)__LINE__, __FUNCTION__, __VA_ARGS__)
 #define assertErrorLog(c, logger, ...) ((c) || errorLog(logger, "Assert " #c " error : " __VA_ARGS__))
 #else
 #define errorLog(logger, ...) (nullptr)
@@ -140,8 +142,8 @@ namespace aFuntool {
 #endif
 
 #if !aFunOFFAllLog
-#define sendErrorLog(logger, ...) getLogger(logger)->writeSendErrorLog(__FILENAME__ , (int)__LINE__, __FUNCTION__, __VA_ARGS__)
-#define fatalErrorLog(logger, exit_code, ...) getLogger(logger)->writeFatalErrorLog(__FILENAME__ , (int)__LINE__, __FUNCTION__, exit_code, __VA_ARGS__)
+#define sendErrorLog(logger, ...) (logger)->writeSendErrorLog(__FILENAME__ , (int)__LINE__, __FUNCTION__, __VA_ARGS__)
+#define fatalErrorLog(logger, exit_code, ...) (logger)->writeFatalErrorLog(__FILENAME__ , (int)__LINE__, __FUNCTION__, exit_code, __VA_ARGS__)
 #define assertSendErrorLog(c, logger, ...) ((c) || sendErrorLog(logger, "Assert " #c " error : " __VA_ARGS__))
 #define assertFatalErrorLog(c, logger, exit_code, ...) ((c) || fatalErrorLog(logger, exit_code, "Assert " #c " error : " __VA_ARGS__))
 #else

+ 13 - 0
include/tool/log.inline.h

@@ -0,0 +1,13 @@
+#ifndef AFUN_LOG_INLINE_H
+#define AFUN_LOG_INLINE_H
+#include "log.h"
+
+namespace aFuntool {
+    inline aFuntool::Logger::Logger(LogFactory &factor, std::string id, LogLevel level, bool exit) noexcept
+        : factor_{factor}, id_ {std::move(id)} {
+        level_ = level;
+        exit_ = exit;
+    }
+}
+
+#endif //AFUN_LOG_INLINE_H

+ 14 - 4
include/tool/mem.inline.h

@@ -3,6 +3,8 @@
 
 #include <cstdlib>
 #include "log.h"
+#include "exit_.h"
+#include "tool-logger.h"
 
 /* 取代calloc函数 */
 namespace aFuntool {
@@ -11,16 +13,24 @@ namespace aFuntool {
 
     static void *safeCalloc(size_t n, size_t size){
         void *re = calloc(n, size);
-        if (re == nullptr)
-            fatalErrorLog(nullptr, EXIT_FAILURE, "The memory error");
+        if (re == nullptr) {
+            if (SysLogger)
+                fatalErrorLog(SysLogger, EXIT_FAILURE, "The memory error");
+            else
+                aFunExit(EXIT_FAILURE);
+        }
         return re;
     }
 
     template <typename T>
     static void *safeCalloc(size_t n, T &t){
         void *re = calloc(n, sizeof(decltype(*t)));  // 自动推断类型
-        if (re == nullptr)
-            fatalErrorLog(nullptr, EXIT_FAILURE, "The memory error");
+        if (re == nullptr) {
+            if (SysLogger)
+                fatalErrorLog(SysLogger, EXIT_FAILURE, "The memory error");
+            else
+                aFunExit(EXIT_FAILURE);
+        }
         return re;
     }
 }

+ 2 - 2
include/tool/regex.h

@@ -15,13 +15,13 @@ namespace aFuntool {
     public:
         explicit Regex(std::string pattern_);
         Regex(const Regex &regex);
-        Regex(Regex &&regex) noexcept;
+        inline Regex(Regex &&regex) noexcept;
         Regex &operator=(const Regex &regex)=delete;
         Regex &operator=(Regex &&regex)=delete;
 
         ~Regex ();
         int match(const char *subject);
-        int match(const std::string &subject);
+        inline int match(const std::string &subject);
     };
 }
 

+ 14 - 0
include/tool/tool-logger.h

@@ -0,0 +1,14 @@
+#ifndef AFUN_TOOL_LOGGER_H
+#define AFUN_TOOL_LOGGER_H
+#include "aFunToolExport.h"
+
+namespace aFuntool {
+    class Logger;
+    extern AFUN_TOOL_EXPORT class Logger *SysLogger;
+
+    static void setSysLogger(aFuntool::Logger *log) {
+        SysLogger = log;
+    }
+}
+
+#endif //AFUN_TOOL_LOGGER_H

+ 4 - 8
src/core/init.cpp

@@ -15,12 +15,8 @@ namespace aFuncore {
  * @return 是否初始化成功
  */
 bool aFuncore::aFunCoreInit(aFuncore::InitInfo *info) {
-    if (info == nullptr) {
-        static InitInfo info_default = {.base_dir=".",
-                                        .log_asyn=true,
-                                        .level=log_info};
-        info = &info_default;
-    }
+    if (info == nullptr)
+        return false;
 
     getEndian();
     if (setlocale(LC_ALL, "") == nullptr)
@@ -32,11 +28,11 @@ bool aFuncore::aFunCoreInit(aFuncore::InitInfo *info) {
     varlib_path = info->base_dir + SEP + aFunVarLibDir + SEP;
 
     std::string log = log_path + "aFunlang";
-    bool re = log_factory.initLogSystem(log, info->log_asyn);
+    bool re = info->factor.initLogSystem(log, info->log_asyn);
     if (re == 0)
         return false;
 
-    static aFuntool::Logger logger {"aFunlang-core", info->level};
+    static aFuntool::Logger logger {info->factor, "aFunlang-core", info->level};
     aFuncore::aFunCoreLogger = &logger;
 
     debugLog(aFunCoreLogger, "aFunCore log path: %s", log_path.c_str());

+ 2 - 1
src/tool/file.cpp

@@ -242,7 +242,8 @@ bool aFuntool::isCharUTF8(const char *str) {
         unsigned char c = *ch;
         unsigned char c_ = ~c;
 
-        assertFatalErrorLog(code >= 0 && code <= 5, nullptr, 2, "str = %s", str);
+        if (SysLogger)
+            assertFatalErrorLog(code >= 0 && code <= 5, SysLogger, 2, "str = %s", str);
         if (code == 0) {
             if ((c_ & 0xFC) == 0 && (c & 0x02) == 0)  // 检查是否为1111110x, 先对其取反, 使用0xFC掩码检查前6位是否为0, 然后单独检查倒数第二位是否为0
                 code = 5;  // 剩余 5 个字节

+ 75 - 106
src/tool/log.cpp

@@ -18,7 +18,7 @@
 #include "tool.h"
 #include "log.h"
 #include "exception.h"
-#include "log-m.h"
+#include "log-macro.h"
 #include "time_.h"
 #include "file.h"
 #include "stdio_.h"
@@ -56,22 +56,19 @@ namespace aFuntool {
 
         LogNode *next = nullptr;
     };
-
-    LogFactory log_factory {};  // NOLINT
 }
 
-static void destructLogSystemAtExit(void *);
 void staticAnsyWritrLog(LogFactory::ansyData *data);
 
-aFuntool::LogFactory::LogFactory() : sys_log("SYSTEM", log_info) {
-    init=false;
-    pid=0;
-    log = nullptr;
-    csv = nullptr;
+aFuntool::LogFactory::LogFactory() : sys_log {*this, "SYSTEM", log_info} {
+    init_=false;
+    pid_=0;
+    log_ = nullptr;
+    csv_ = nullptr;
 
-    asyn=false;
-    log_buf = nullptr;
-    plog_buf = nullptr;
+    asyn_=false;
+    log_buf_ = nullptr;
+    plog_buf_ = nullptr;
 }
 
 /**
@@ -92,13 +89,13 @@ int aFuntool::LogFactory::initLogSystem(ConstFilePath path, bool is_asyn){
         return 0;
 
     int re = 1;
-    std::unique_lock<std::mutex> ul{mutex};
-    if (init)
+    std::unique_lock<std::mutex> ul{mutex_};
+    if (init_)
         return 2;
 
     char log_path[218] = {0};
     char csv_path[218] = {0};
-    pid = getpid();  // 获取进程ID
+    pid_ = getpid();  // 获取进程ID
 
     char *ti = getTime(nullptr, (char *)"%Y-%m-%d%z");
     snprintf(log_path, 218, "%s-%s.log", path.c_str(), ti);
@@ -109,77 +106,60 @@ int aFuntool::LogFactory::initLogSystem(ConstFilePath path, bool is_asyn){
     uintmax_t csv_size = getFileSize(csv_path);
     bool csv_head_write = (checkFile(csv_path) == 0);  // 文件不存在时才写入头部
 
-    log = fileOpen(log_path, "a");
-    if (log == nullptr) {
+    log_ = fileOpen(log_path, "a");
+    if (log_ == nullptr) {
         perror("ERROR: ");
         return 0;
     }
 
-    csv = fileOpen(csv_path, (char *)"a");
-    if (csv == nullptr)
+    csv_ = fileOpen(csv_path, (char *)"a");
+    if (csv_ == nullptr)
         return 0;
 
 #define CSV_FORMAT "%s,%s,%d,%d,%s,%ld,%s,%d,%s,%s\n"
 #define CSV_TITLE  "Level,Logger,PID,TID,Data,Timestamp,File,Line,Function,Log\n"
     if (csv_head_write) {
-        fprintf(csv, CSV_TITLE);  // 设置 cvs 标题
-        fflush(csv);
+        fprintf(csv_, CSV_TITLE);  // 设置 cvs 标题
+        fflush(csv_);
     }
 #undef CSV_TITLE
 
-    init = true;
-    asyn = is_asyn;
+    init_ = true;
+    asyn_ = is_asyn;
     if (is_asyn) {
-        plog_buf = &log_buf;
-        auto *data = new ansyData;
-        data->mutex = &mutex;
-        pt = std::thread(staticAnsyWritrLog, data);
+        plog_buf_ = &log_buf_;
+        auto *data = new ansyData{*this, mutex_};
+        thread_ = std::thread(staticAnsyWritrLog, data);
     }
 
     ul.unlock();
-    infoLog(nullptr, "Log system init success");
-    infoLog(nullptr, "Log .log size %lld", log_size);
-    infoLog(nullptr, "Log .csv size %lld", csv_size);
-    aFunAtExit(destructLogSystemAtExit, nullptr);
+    infoLog(&this->sys_log, "Log system init success");
+    infoLog(&this->sys_log, "Log .log size %lld", log_size);
+    infoLog(&this->sys_log, "Log .csv size %lld", csv_size);
     return re;
 }
 
-static void destructLogSystemAtExit(void *) {
-    log_factory.destruct();
-}
-
 aFuntool::LogFactory::~LogFactory(){
-    destruct();
-}
-
-bool aFuntool::LogFactory::destruct() {
-    bool re = true;
-    std::unique_lock<std::mutex> ul{mutex};
-    if (!init) {
-        re = false;
-        goto RETURN;
-    }
+    std::unique_lock<std::mutex> ul{mutex_};
 
     ul.unlock();
-    infoLog(nullptr, "Log system destruct by exit.");  // 需要用锁
+    infoLog(&this->sys_log, "Log system destruct by exit.");  // 需要用锁
 
     ul.lock();
-    init = false;
-    if (asyn) {
+    init_ = false;
+    if (asyn_) {
         ul.unlock();
-        cond.notify_all();
-        pt.join();
+        cond_.notify_all();
+        thread_.join();
         ul.lock();
-        if (log_buf != nullptr)
+        if (log_buf_ != nullptr)
             printf_stderr(0, "Logsystem destruct error.");
     }
 
-    fileClose(log);
-    fileClose(csv);
-    log = nullptr;
-    csv = nullptr;
-RETURN:
-    return re;
+    fileClose(log_);
+    fileClose(csv_);
+    log_ = nullptr;
+    csv_ = nullptr;
 }
 
 
@@ -224,13 +204,13 @@ void aFuntool::LogFactory::writeLog(LogLevel level,
                                const char *info) {
 #define FORMAT "%s/[%s] %d %d {%s %ld} (%s:%d at %s) : '%s' \n"
     /* 写入文件日志 */
-    if (log != nullptr) {
-        fprintf(log, FORMAT, LogLevelName[level], id, pid, tid, ti, t, file, line, func, info);
-        fflush(log);
+    if (log_ != nullptr) {
+        fprintf(log_, FORMAT, LogLevelName[level], id, pid_, tid, ti, t, file, line, func, info);
+        fflush(log_);
     }
-    if (csv != nullptr) {
-        fprintf(csv, CSV_FORMAT, LogLevelName[level], id, pid, tid, ti, t, file, line, func, info);
-        fflush(csv);
+    if (csv_ != nullptr) {
+        fprintf(csv_, CSV_FORMAT, LogLevelName[level], id, pid_, tid, ti, t, file, line, func, info);
+        fflush(csv_);
     }
 
 #undef FORMAT
@@ -283,8 +263,8 @@ void aFuntool::LogFactory::writeLogAsyn(LogLevel level,
                                         const char *id, pid_t tid,
                                         const char *ti, time_t t,
                                         const char *file, int line, const char *func, const char *info) {
-#define D(i) (*(plog_buf))->i
-    *(plog_buf) = new aFuntool::LogNode;
+#define D(i) (*(plog_buf_))->i
+    *(plog_buf_) = new aFuntool::LogNode;
     D(level) = level;
     D(id) = id;
     D(tid) = tid;
@@ -294,24 +274,24 @@ void aFuntool::LogFactory::writeLogAsyn(LogLevel level,
     D(line) = line;
     D(func) = func;
     D(info) = strCopy(info);
-    log_factory.plog_buf = &(D(next));
+    plog_buf_ = &(D(next));
 #undef D
 }
 
 
 aFuntool::LogNode *aFuntool::LogFactory::pop(){
-    struct LogNode *n = log_buf;
+    struct LogNode *n = log_buf_;
     if (n != nullptr) {
-        log_buf = n->next;
-        if (log_buf == nullptr)
-            plog_buf = &log_buf;
+        log_buf_ = n->next;
+        if (log_buf_ == nullptr)
+            plog_buf_ = &log_buf_;
     }
     return n;
 }
 
 
 void staticAnsyWritrLog(LogFactory::ansyData *data) {
-    log_factory.ansyWritrLog(data);
+    data->factor.ansyWritrLog(data);
 }
 
 
@@ -320,16 +300,16 @@ void staticAnsyWritrLog(LogFactory::ansyData *data) {
  * @return
  */
 void LogFactory::ansyWritrLog(ansyData *data) {
-    std::unique_lock<std::mutex> ul{mutex};
+    std::unique_lock<std::mutex> ul{mutex_};
     while (true) {
-        while (init && log_buf == nullptr)
-            cond.wait(ul);
-        if (!init && log_buf == nullptr)
+        while (init_ && log_buf_ == nullptr)
+            cond_.wait(ul);
+        if (!init_ && log_buf_ == nullptr)
             break;
 
-        LogNode *tmp = log_factory.pop();
+        LogNode *tmp = data->factor.pop();
 #define D(i) tmp->i
-        log_factory.writeLog(D(level), D(id), D(tid), D(date), D(time), D(file), D(line), D(func), D(info));
+        data->factor.writeLog(D(level), D(id), D(tid), D(date), D(time), D(file), D(line), D(func), D(info));
 #undef D
         free(tmp->date);
         free(tmp->info);
@@ -355,14 +335,14 @@ int aFuntool::LogFactory::newLog(Logger *logger,
                                  LogLevel level,
                                  const char *file, int line, const char *func,
                                  const char *format, va_list ap){
-    if (logger->level > level)
+    if (logger->level_ > level)
         return 2;
 
-    std::unique_lock<std::mutex> ul{mutex};
-    if (!init || log == nullptr) {
+    std::unique_lock<std::mutex> ul{mutex_};
+    if (!init_ || log_ == nullptr) {
         return 1;
     }
-    clear_ferror(log);
+    clear_ferror(log_);
 
     // 输出 head 信息
     time_t t = 0;
@@ -373,36 +353,28 @@ int aFuntool::LogFactory::newLog(Logger *logger,
     vsnprintf(tmp, 1024, format, ap);  // ap只使用一次
     va_end(ap);
 
-    if (asyn)
-        writeLogAsyn(level, logger->id.c_str(), tid, ti, t, file, line, func, tmp);
+    if (asyn_)
+        writeLogAsyn(level, logger->id_.c_str(), tid, ti, t, file, line, func, tmp);
     else
-        writeLog(level, logger->id.c_str(), tid, ti, t, file, line, func, tmp);
+        writeLog(level, logger->id_.c_str(), tid, ti, t, file, line, func, tmp);
 
     if (pc)
-        writeConsole(level, logger->id.c_str(), tid, ti, t, file, line, func, tmp);
+        writeConsole(level, logger->id_.c_str(), tid, ti, t, file, line, func, tmp);
 
     ul.unlock();
-    if (asyn)
-        cond.notify_all();
+    if (asyn_)
+        cond_.notify_all();
     free(ti);
     return 0;
 }
 
-#define CHECK_LOGGER() do {if (logger == nullptr) {logger = &(log_factory.sys_log);} \
-                           if (logger == nullptr) return -1;} while(0)
-
-aFuntool::Logger::Logger(const std::string &id_, LogLevel level_, bool exit_) : id {id_} {
-    this->level = level_;
-    this->exit = exit_;
-}
-
 #undef trackLog
 int aFuntool::Logger::writeTrackLog(const char *file, int line, const char *func,
                                     const char *format, ...) {
 #if aFunWriteTrack
     va_list ap;
     va_start(ap, format);
-    return log_factory.newLog(this, aFunConsoleTrack, log_track, file, line, func, format, ap);
+    return this->factor_.newLog(this, aFunConsoleTrack, log_track, file, line, func, format, ap);
 #endif
 }
 
@@ -412,7 +384,7 @@ int aFuntool::Logger::writeDebugLog(const char *file, int line, const char *func
 #if aFunWriteDebug
     va_list ap;
     va_start(ap, format);
-    return log_factory.newLog(this, aFunConsoleDebug, log_debug, file, line, func, format, ap);
+    return this->factor_.newLog(this, aFunConsoleDebug, log_debug, file, line, func, format, ap);
 #endif
 }
 
@@ -422,7 +394,7 @@ int aFuntool::Logger::writeInfoLog(const char *file, int line, const char *func,
 #if aFunWriteInfo
     va_list ap;
     va_start(ap, format);
-    return log_factory.newLog(this, aFunConsoleInfo, log_info, file, line, func, format, ap);
+    return this->factor_.newLog(this, aFunConsoleInfo, log_info, file, line, func, format, ap);
 #endif
 }
 
@@ -432,7 +404,7 @@ int aFuntool::Logger::writeWarningLog(const char *file, int line, const char *fu
 #if !aFunIgnoreWarning
     va_list ap;
     va_start(ap, format);
-    return log_factory.newLog(this, aFunConsoleWarning, log_warning, file, line, func, format, ap);
+    return this->factor_.newLog(this, aFunConsoleWarning, log_warning, file, line, func, format, ap);
 #endif
 }
 
@@ -442,7 +414,7 @@ int aFuntool::Logger::writeErrorLog(const char *file, int line, const char *func
 #if !aFunIgnoreError
     va_list ap;
     va_start(ap, format);
-    return log_factory.newLog(this, aFunConsoleError, log_error, file, line, func, format, ap);
+    return this->factor_.newLog(this, aFunConsoleError, log_error, file, line, func, format, ap);
 #endif
 }
 
@@ -453,12 +425,11 @@ int aFuntool::Logger::writeSendErrorLog(const char *file, int line, const char *
 #if !aFunIgnoreSendError
     va_list ap;
     va_start(ap, format);
-    log_factory.newLog(this, aFunConsoleSendError, log_send_error, file, line, func, format, ap);
+    this->factor_.newLog(this, aFunConsoleSendError, log_send_error, file, line, func, format, ap);
 #endif
 
-    if (this->exit)
+    if (this->exit_)
         throw LogFatalError("Log Fatal Error");
-    aFuntool::log_factory.destruct();
     aFunExit(EXIT_FAILURE);
 #endif
 }
@@ -470,10 +441,8 @@ int aFuntool::Logger::writeFatalErrorLog(const char *file, int line, const char
 #if !aFunIgnoreFatal
     va_list ap;
     va_start(ap, format);
-    log_factory.newLog(this, aFunConsoleFatalError, log_fatal_error, file, line, func, format, ap);
+    this->factor_.newLog(this, aFunConsoleFatalError, log_fatal_error, file, line, func, format, ap);
 #endif
-
-    aFuntool::log_factory.destruct();
     if (exit_code == EXIT_SUCCESS)
         abort();
     else

+ 5 - 0
src/tool/tool-logger.cpp

@@ -0,0 +1,5 @@
+#include "tool-logger.h"
+
+namespace aFuntool {
+    Logger *SysLogger = nullptr;
+}

+ 2 - 0
test/src/core-init.cpp

@@ -9,7 +9,9 @@ int main() {
         aFunExit(EXIT_FAILURE);
     }
 
+    aFuntool::LogFactory factor {};
     aFuncore::InitInfo info = {.base_dir=base_path,
+                               .factor=factor,
                                .log_asyn=true,
                                .level=log_debug,
     };

+ 4 - 2
test/src/tool-logger.cpp

@@ -9,9 +9,11 @@ int main(int argc, char **argv){
     }
 
     setlocale(LC_ALL, "");
-    log_factory.initLogSystem(base_path + SEP + "aFunlog");
 
-    static auto logger = Logger("Test", aFuntool::log_info);
+    static LogFactory factor {};
+    factor.initLogSystem(base_path + SEP + "aFunlog");
+
+    static auto logger = Logger(factor, "Test", aFuntool::log_info);
     infoLog(&logger, "Test logger");
     aFunExit(0);
 }