瀏覽代碼

Z991239-635 #comment feature: 添加厂商日志库跨平台编译

gifur 5 年之前
父節點
當前提交
450482ff91

+ 5 - 1
DevAdapter/self/CMakeLists.txt

@@ -1 +1,5 @@
-add_subdirectory(liblog4vendor)
+set(RVC_VENDOR_LIB_DIRS)
+
+add_subdirectory(liblog4vendor)
+
+set(RVC_VENDOR_DEP_LIB_DIRS ${RVC_VENDOR_DEP_LIB_DIRS} ${RVC_VENDOR_LIB_DIRS} PARENT_SCOPE)

+ 18 - 0
DevAdapter/self/liblog4vendor/CMakeLists.txt

@@ -18,6 +18,7 @@ conan_cmake_run(REQUIRES log4cplus/1.2.1@LR04.02_ThirdParty/stable
 
 add_library(${MODULE_NAME} SHARED ${${MODULE_PREFIX}_SRCS})
 target_include_directories(${MODULE_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
+target_include_directories(${MODULE_NAME} PRIVATE ${DEVADAPTER_CURRENT_INCLUDES_DIR})
 set_target_properties(${MODULE_NAME} PROPERTIES COMPILE_DEFINITIONS "LIBLOG4VENDOR_EXPORTS")
 set_target_properties(${MODULE_NAME} PROPERTIES DEBUG_POSTFIX "d")
 
@@ -25,4 +26,21 @@ if(MSVC)
 list(APPEND OTHER_LIBS Psapi)
 endif(MSVC)
 target_link_libraries(${MODULE_NAME} CONAN_PKG::log4cplus ${OTHER_LIBS})
+if(MSVC)
+    set_target_properties(${MODULE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${DEVADAPTER_CURRENT_BIN_DIR}) 
+else(MSVC)
+    set_target_properties(${MODULE_NAME} PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${DEVADAPTER_CURRENT_LIB_DIR}) 
+endif(MSVC)
+
+rvc_dev_target_install(${MODULE_NAME})
+
+if(MSVC)
+    set(RVC_VENDOR_LIB_DIRS ${RVC_VENDOR_LIB_DIRS} ${CONAN_BIN_DIRS_LOG4CPLUS} PARENT_SCOPE)
+else(MSVC)
+    set(RVC_VENDOR_LIB_DIRS ${RVC_VENDOR_LIB_DIRS} ${CONAN_LIB_DIRS_LOG4CPLUS} PARENT_SCOPE)
+endif(MSVC)
+
+if(BUILD_TESTING)
+    add_subdirectory(test)
+endif(BUILD_TESTING)
 

+ 55 - 24
DevAdapter/self/liblog4vendor/env_deal.cpp

@@ -1,7 +1,9 @@
-#include "StdAfx.h"
-#include "env_deal.h"
+#if defined(_MSC_VER)
+#include "stdafx.h"
+#endif //_MSC_VER
 #include "log4vendor.h"
-
+#include <string.h>
+#include "env_deal.h"
 
 namespace cmb {
 
@@ -11,30 +13,59 @@ namespace cmb {
 
 	bool env_deal::set(const std::string& value)
 	{
-		DWORD dwResult = SetEnvironmentVariableA(str_.c_str(), value.c_str());
-		return (dwResult != 0);
+#if defined(_MSC_VER)
+        DWORD dwResult = SetEnvironmentVariableA(str_.c_str(), value.c_str());
+        return (dwResult != 0);
+#else
+        if (setenv(str_.c_str(), value.c_str(), 1) != 0)
+            return false;
+        return true;
+#endif //_MSC_VER
+
 	}
 
 	bool env_deal::get(std::string& value)
 	{
-		bool res = false;
-		DWORD dwSize;
-		value.clear();
-		dwSize = GetEnvironmentVariableA(str_.c_str(), NULL, 0);
-		if(dwSize > 0) {
-			char* buf = new char[dwSize+1];
-			if(buf == NULL) {
-				return false;
-			}
-			memset(buf, '\0', sizeof(char)*(dwSize+1));
-			dwSize = GetEnvironmentVariableA(str_.c_str(), buf, dwSize);
-			if(dwSize > 0) {
-				value = buf;
-				res = true;
-			}
-			delete[] buf;
-		}
-		return res;
+#if defined(_MSC_VER)
+        bool res = false;
+        DWORD dwSize;
+        value.clear();
+        dwSize = GetEnvironmentVariableA(str_.c_str(), NULL, 0);
+        if (dwSize > 0) {
+            char* buf = new char[dwSize + 1];
+            if (buf == NULL) {
+                return false;
+            }
+            memset(buf, '\0', sizeof(char) * (dwSize + 1));
+            dwSize = GetEnvironmentVariableA(str_.c_str(), buf, dwSize);
+            if (dwSize > 0) {
+                value = buf;
+                res = true;
+            }
+            delete[] buf;
+        }
+        return res;
+#else
+        bool res = false;
+        value.clear();
+        char* var = getenv(str_.c_str());
+        if (var == NULL)
+            return false;
+
+        size_t len = strlen(var);
+        if (len > 0) {
+            char* buf = new char[len + 1];
+            if (buf == NULL) {
+                return false;
+            }
+            memset(buf, '\0', sizeof(char) * (len + 1));
+            memcpy(buf, var, len);
+            value = buf;
+            res = true;
+            delete[] buf;
+        }
+        return res;
+#endif //_MSC_VER
 	}
 
 	env_deal::~env_deal(void)
@@ -47,6 +78,6 @@ namespace cmb {
 		env_deal("VENDOR_RECODE_LEVEL").get(record_level);
 		env_deal("VENDOR_DLL_NAME").get(module_name);
 		env_deal("VENDOR_LOG_PATH").get(record_path);
-		return true;
+        return true;
 	}
 }

+ 0 - 1
DevAdapter/self/liblog4vendor/env_deal.h

@@ -3,7 +3,6 @@
 
 #pragma once
 
-#include <Windows.h>
 #include <string>
 
 namespace cmb {

+ 48 - 8
DevAdapter/self/liblog4vendor/liblog4vendor.cpp

@@ -3,14 +3,20 @@
 
 #include "liblog4vendor.h"
 #include <stdio.h>
-#include <Psapi.h>
-
-BOOL GetCurProcessPath(char szPath[], DWORD dwPathSize);
 
+#if OS_WIN
+#include <Psapi.h>
 #define CUR_PROCESS_NAME "sphost.exe"
-
 static HMODULE gModule = NULL;
-static INT IsSphostExe = -1;
+#else
+#include <string.h>
+#include <sys/types.h>
+#include <unistd.h>
+#define CUR_PROCESS_NAME "sphost"
+#endif
+static int IsSphostExe = -1;
+
+BOOL GetCurProcessPath(char szPath[], DWORD dwPathSize);
 
  /*!
  * @brief detect current process is created by VTM
@@ -20,9 +26,8 @@ static INT IsSphostExe = -1;
 EXTERN_C BOOL IsVTMProcess()
 {
 	if(IsSphostExe == -1) {
-		BOOL retVal = FALSE;
-		char szPath[MAX_PATH] = {'\0'};
-		DWORD dwPathSize = MAX_PATH;
+		char szPath[4096] = {'\0'};
+		DWORD dwPathSize = 4096;
 		if(GetCurProcessPath(szPath, dwPathSize)) {
 			char* pos = strstr(szPath, CUR_PROCESS_NAME);
 			dwPathSize = strlen(szPath);
@@ -41,6 +46,9 @@ EXTERN_C BOOL IsVTMProcess()
 
 EXTERN_C BOOL GetCurFileVersion(char szVerion[], DWORD dwVerionSize)
 {
+
+#if OS_WIN
+
 	HRSRC hsrc=FindResourceA(gModule, MAKEINTRESOURCE(VS_VERSION_INFO), RT_VERSION);
 	HGLOBAL hgbl = LoadResource(gModule, hsrc);
 	BYTE *pBt = (BYTE *)LockResource(hgbl);
@@ -51,9 +59,13 @@ EXTERN_C BOOL GetCurFileVersion(char szVerion[], DWORD dwVerionSize)
 		(pFinfo->dwFileVersionLS >> 16) & 0xFF,
 		(pFinfo->dwFileVersionLS) & 0xFF);
 
+#endif
+
 	return TRUE;
 }
 
+#if OS_WIN
+
 BOOL APIENTRY DllMain( HMODULE hModule,
 	DWORD  ul_reason_for_call,
 	LPVOID lpReserved
@@ -105,4 +117,32 @@ BOOL GetCurProcessPath(char szPath[], DWORD dwPathSize)
 
 }
 
+#else
+
+BOOL GetCurProcessPath(char szPath[], DWORD dwPathSize)
+{
+    int status;
+    size_t length;
+    char path[64];
+    char buffer[4096];
+	snprintf(path, 64, "/proc/%d/exe", getpid());
+    status = readlink(path, buffer, sizeof(buffer));
+    if (status < 0) {
+        return FALSE;
+    }
+
+    buffer[status] = '\0';
+    length = strnlen(buffer, sizeof(buffer));
+	memset(szPath, '\0', sizeof(szPath[0]) * dwPathSize);
+    if (length < dwPathSize) {
+		memcpy(szPath, buffer, length);
+		szPath[length] = '\0';
+        return TRUE;
+    }
+
+	memcpy(szPath, buffer, dwPathSize - 1);
+	szPath[dwPathSize - 1] = '\0';
+    return FALSE;
+}
 
+#endif

+ 44 - 4
DevAdapter/self/liblog4vendor/liblog4vendor.h

@@ -1,14 +1,54 @@
+#ifndef RVC_VENDOR_LOG4VENDOR_H_
+#define RVC_VENDOR_LOG4VENDOR_H_
+
 #pragma once
 
-#include <SDKDDKVer.h>
+#if (defined(_WIN32) || defined(_WIN64))
+#define OS_WIN 1
+#else
+#define OS_WIN 0
+#endif
 
-#ifndef WIN32_LEAN_AND_MEAN
-    #define WIN32_LEAN_AND_MEAN             //  从 Windows 头文件中排除极少使用的信息
+#ifndef _WIN32
+
+#include <stdint.h>
+
+#ifdef __cplusplus
+#define EXTERN_C       extern "C"
+#define EXTERN_C_START extern "C" {
+#define EXTERN_C_END   }
+#else
+#define EXTERN_C       extern
+#define EXTERN_C_START
+#define EXTERN_C_END
 #endif
 
+typedef uint8_t BYTE;
+typedef uint8_t* LPBYTE;
+typedef uint16_t WORD;
+typedef uint32_t DWORD;
+typedef char CHAR;
+typedef uint8_t BOOL;
+
+#define TRUE 1
+#define FALSE 0
+
+#ifndef MAX_PATH
+#define MAX_PATH 260
+#endif
+
+#else
+
+#include <SDKDDKVer.h>
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN             //  从 Windows 头文件中排除极少使用的信息
+#endif
 // Windows 头文件:
 #include <windows.h>
+#endif
 
 EXTERN_C BOOL IsVTMProcess();
 
-EXTERN_C BOOL GetCurFileVersion(char szVerion[], DWORD dwVerionSize);
+EXTERN_C BOOL GetCurFileVersion(char szVerion[], DWORD dwVerionSize);
+
+#endif

+ 43 - 10
DevAdapter/self/liblog4vendor/log4cplus_helper.cpp

@@ -1,17 +1,13 @@
 #include "log4cplus_helper.h"
 #include <iostream>
 #include <string>
+#include <string.h>
 
 #if defined(_WIN32) && defined (LOG4CPLUS_HAVE_WIN32_CONSOLE)
 #include <log4cplus/win32consoleappender.h>
 #define WIN32_CONSOLE 1
 #endif
 
-#if defined(ANDROID)
-#include <android/log.h>
-static const char* TAG = "lib";
-#endif
-
 using namespace log4cplus;
 using namespace log4cplus::helpers;
 
@@ -21,8 +17,10 @@ using namespace log4cplus::helpers;
 	LOG4CPLUS_##TYPE(LOGGER, msg);
 
 
+
 static inline vtm_string w2s(const std::wstring wstr)
 {
+#if defined(_MSC_VER)
 	char* str = NULL;
 	int n = ::WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, NULL, 0, NULL, NULL);
 	if (n > 0) {
@@ -37,8 +35,30 @@ static inline vtm_string w2s(const std::wstring wstr)
 		return strr;
 	}
 	return vtm_string();
+
+#else
+
+    if (wstr.empty())
+    {
+        return "";
+    }
+    unsigned len = wcstombs(NULL, wstr.c_str(), 0) + 1;
+    if (NULL == setlocale(LC_ALL, "zh_CN.gbk"))
+    {
+
+    }
+    char* p = new char[len];
+    wcstombs(p, wstr.c_str(), len);
+    p[len - 1] = '\0';
+    std::string str(p);
+    delete[] p;
+    return str;
+
+#endif // _MSC_VER
 }
 
+
+
 namespace cmb {
 
 	log4cplus_helper* log4cplus_helper::_instance = NULL;
@@ -94,7 +114,7 @@ namespace cmb {
 #else
 		LogLog::getLogLog()->setInternalDebugging(false);
 #endif
-		log4cplus::Logger& logger = get_logger();
+		log4cplus::Logger logger = get_logger();
 		logger.setLogLevel(_log_level);
 		
 		if ((_append_type & log_append_console) == log_append_console)
@@ -116,7 +136,11 @@ namespace cmb {
 			vtm_string log_path(_log_dir);
 			assert(!log_path.empty());
 			log_path += name;
-			log_path += LOG4CPLUS_TEXT("\\");		
+#if defined(_MSC_VER)
+			log_path += LOG4CPLUS_TEXT("\\");
+#else
+			log_path += LOG4CPLUS_TEXT("/");
+#endif //_MSC_VER	
 			tstring str(LOG4CPLUS_TEXT("FilenamePattern="));
 			str += log_path;
 			str += LOG4CPLUS_TEXT("%d{yyyyMMdd}.log\n");
@@ -180,7 +204,11 @@ namespace cmb {
 			vtm_string log_path(_log_dir);
 			assert(!log_path.empty());
 			log_path += remote_name;
+#if defined(_MSC_VER)
 			log_path += "\\";
+#else
+			log_path += "/";
+#endif //_MSC_VER
 			tstring str(LOG4CPLUS_TEXT("FilenamePattern="));
 			str += log_path;
 			str += LOG4CPLUS_TEXT("%d{yyyyMMdd}.log\n");
@@ -381,9 +409,14 @@ namespace cmb {
 		int len = 0;
 		vtm_string formatted = "";
 		char* buffer = NULL;
-		len =  _vscprintf( ft, arg ) + 1;
-		buffer = (char*)malloc( len * sizeof(char) );
-		len = vsprintf_s(buffer,len,ft, arg);
+#if defined(_WIN32)
+        len = _vscprintf(ft, arg) + 1;
+        buffer = (char*)malloc(len * sizeof(char));
+        len = vsprintf_s(buffer, len, ft, arg);
+#else
+        buffer = (char*)malloc(MAX_BUFFER_LENGTH + 1);
+        sprintf(buffer, ft, arg);
+#endif
 		formatted = buffer ;
 		free(buffer);
 		return formatted;

+ 5 - 1
DevAdapter/self/liblog4vendor/log4cplus_helper.h

@@ -93,8 +93,12 @@ namespace cmb {
 			if(tmp.empty()) 
 				return false;
 			if(tmp[tmp.size()-1] != '\\' && tmp[tmp.size()-1] != '/') {
+#if defined(_MSC_VER)
 				tmp.push_back('\\');
-			}
+#else
+				tmp.push_back('/');
+#endif //_MSC_VER
+			} 
 			_log_dir = tmp;
 			return true;
 		}

+ 24 - 10
DevAdapter/self/liblog4vendor/log4vendor.cpp

@@ -3,6 +3,20 @@
 #include "log4cplus_helper.h"
 #include "env_deal.h"
 #include <vector>
+#ifndef _WIN32
+#include<sys/types.h>
+#include <unistd.h>
+#include <string.h>
+#else
+#include <process.h>
+#endif //NOT _WIN32
+
+#if defined(_MSC_VER)
+#define LIBRARY_POSIXNAME "DLL"
+#else
+#define LIBRARY_POSIXNAME "SO"
+
+#endif //_MSC_VER
 
 namespace cmb {
 
@@ -87,7 +101,7 @@ namespace cmb {
 
 		auto dev_infos = split(env.module_name, '.');
 		//TODO: comfirm the name's validity. {DeviceName}.{VendorName}.{X}.{Y}.dll
-		if(dev_infos.size() == 5 && toupper(dev_infos[4]) == "DLL") {
+		if(dev_infos.size() == 5 && toupper(dev_infos[4]) == LIBRARY_POSIXNAME) {
 			config->dev_name = "vendor_";
 			config->dev_name += dev_infos[0];
 		}
@@ -119,7 +133,7 @@ namespace cmb {
 					env_string = log_config.module_name;
 				}
 			} else {
-				ret_msg = env_string + "WARN: vtm runtime, retrieve config failed.";
+				ret_msg = env_string + " WARN: vtm runtime, retrieve config failed.";
 				goto error_point;
 			}
 		} else {
@@ -127,22 +141,22 @@ namespace cmb {
 		}
 
 		if(!log4cplus_helper::get_instance()->set_log_append_type(lhs->log_type)) {
-			ret_msg = env_string + "ERROR: set log type failed.";
+			ret_msg = env_string + " -- ERROR: set log type failed.";
 			goto error_point;
 		}
 
 		if(!log4cplus_helper::get_instance()->set_log_level(lhs->log_level)) {
-			ret_msg = env_string + "ERROR: set log level failed.";
+			ret_msg = env_string + " -- ERROR: set log level failed.";
 			goto error_point;
 		}
 
 		if(!log4cplus_helper::get_instance()->set_log_dir(lhs->log_dir)) {
-			ret_msg = env_string + "ERROR: set log dir failed.";
+			ret_msg = env_string + " -- ERROR: set log dir failed.";
 			goto error_point;
 		}
 
 		if(!log4cplus_helper::get_instance()->init(lhs->dev_name.c_str())) {
-			ret_msg = env_string + "ERROR: real init failed.";
+			ret_msg = env_string + " -- ERROR: real init failed.";
 			goto error_point;
 		}
 		instance_name = lhs->dev_name;
@@ -154,21 +168,21 @@ namespace cmb {
 		log4plus_initialized = true;
 
 		LOG4VTM(INFO, "==============Log4Vendor(" << instance_name << ") start==============");
-		LOG4VTM(INFO, "process id: " << GetCurrentProcessId());
+		LOG4VTM(INFO, "process id: " << getpid());
 		{
 			char ver[128] = {'\0'};
 			DWORD sz = 128;
 			GetCurFileVersion(ver, sz);
 			LOG4VTM(INFO, "log4vendor instance' s version: " << ver);
 		}
-
-		
 		return;
 
 error_point:
 
 		std::string ps = ret_msg + "\n";
+#if defined(_MSC_VER)
 		OutputDebugStringA(ps.c_str());
+#endif //_MSC_VER
 	}
 
 	/*获取输出字符串流引用对象,不自己定义,从开源库中获取会比较安全*/
@@ -198,7 +212,7 @@ error_point:
 		str << "==> Enter {" << m_pszMes << "}, file: {" << m_pszFileN << "}, line: {" << m_nLine << "}.";
 		log4cplus_helper::get_instance()->trace(str.str());
 	}
-	log4vendor_tracer::log4vendor_tracer(const char* message, const char* fileName, int nLine, unsigned long* pRet)
+	log4vendor_tracer::log4vendor_tracer(const char* message, const char* fileName, int nLine, PDWORD pRet)
 		:m_pszMes(message), m_pszFileN(fileName), m_nLine(nLine)
 		, m_pnRet(NULL), m_pDwRet(pRet), m_pfRet(NULL), m_retType(1)
 	{

+ 0 - 197
DevAdapter/self/liblog4vendor/log4vendor.h

@@ -1,197 +0,0 @@
- /***********************************//**
- * @file log4vendor.h
- * @email guifaliao@gmail.com
- * @version 0.0.0.1
- * @date 2020-04-28
- * @copyright China Merchants Bank Co.,Ltd All rights reserved
- *
- * @brief Log class for VTM device vendor for developing device adapter
- * @details 
- *	2020-4-28: strip log component from SpAgent Project and adjust it.
- *  
- **************************************/
-
-#ifndef _VTM_LOG4VENDOR_H_
-#define _VTM_LOG4VENDOR_H_
-
-#pragma once
-
-#include <sstream>
-#include <string>
-
-#ifdef _WIN32
-#ifdef LIBLOG4VENDOR_EXPORTS
-#define LOG4VENDOR_API __declspec(dllexport)
-#else
-#define LOG4VENDOR_API __declspec(dllimport)
-#endif
-#else
-#if ( defined(__GNUC__) &&  __GNUC__ >= 4 )
-#define LOG4VENDOR_API __attribute__((visibility("default")))
-#else
-#define LOG4VENDOR_API
-#endif
-#endif
-
-#ifdef UNICODE
-#error This version is not support {UNICODE} char set!!
-#define LOG4VTM_TEXT2(STRING) L##STRING
-typedef std::wstring vtm_string;
-typedef wchar_t vtm_char;
-#else
-#define LOG4VTM_TEXT2(STRING) STRING
-typedef std::string vtm_string;
-typedef char vtm_char;
-#endif // UNICODE
-#define LOG4VTM_TEXT(STRING) LOG4VTM_TEXT2(STRING)
-
-
-#define CMB_LOG_TYPE_CONSOLE 1   /*控制台输出*/
-#define CMB_LOG_TYPE_FILE    2   /*文件记录输出*/
-#define CMB_LOG_TYPE_SOCKET  4   /*TCP传输输出,暂未实现*/
-
-#define CMB_LOG_LEVEL_OFF     6  /*关闭任何日志输出*/
-#define CMB_LOG_LEVEL_FATAL   5  /*非常严重类型的日志输出*/
-#define CMB_LOG_LEVEL_ERROR   4  /*错误类型的日志输出*/
-#define CMB_LOG_LEVEL_WARN    3  /*告警类型的日志输出*/
-#define CMB_LOG_LEVEL_INFO    2  /*普通日志输出*/
-#define CMB_LOG_LEVEL_DEBUG   1  /*调试日志输出*/
-#define CMB_LOG_LEVEL_TRACE   0  /*跟踪函数进出等输出*/
-#define CMB_LOG_LEVEL_ALL     CMB_LOG_LEVEL_TRACE
-
-#define CMB_LOG_TRACE   1
-#define CMB_LOG_DEBUG   2
-#define CMB_LOG_INFO    3
-#define CMB_LOG_WARN    4
-#define CMB_LOG_ERROR   5
-#define CMB_LOG_FATAL   6
-//#define CMB_LOG_ASSERT  7
-
-#define CMB_INSTANTIATE_OSTRINGSTREAM(var)                              \
-	std::basic_ostringstream<char>& var                                 \
-	= cmb::log4vendor::get_oss()
-
-#define CMB_LOG_BODY(logLevel, logEvent)                                \
-	__pragma (warning (push))                                           \
-	__pragma (warning (disable:4127))                                   \
-    do {                                                                \
-        cmb::log4vendor* _l                                             \
-            = cmb::log4vendor::instance();                              \
-		CMB_INSTANTIATE_OSTRINGSTREAM (_log4cplus_buf);                 \
-		_log4cplus_buf << logEvent;                                     \
-        _l->log(logLevel, _log4cplus_buf.str());                        \
-    } while (0)                                                         \
-    __pragma (warning (pop))
-
-
- /*!
- * @brief 打印日志的函数,所有等级的日志打印均通过该宏调用实现
- * @param[in]  
- *		severity: 日志等级 TRACE, INFO, WARN, ERROR, FATAL, ASSERT
- *		ostr:     要打印的内容,支持 << 连续输出
- */
-#define LOG4VTM(severity, ostr)                                        \
-    CMB_LOG_BODY(CMB_LOG_ ## severity, ostr)
-
- /*!
- * @brief: 用于记录函数进出的宏定义,在进入目的函数时立即调用,在该函数退出时会打印日志
-/**/
-#define LOG4VTM_FUNCTION() cmb::log4vendor_tracer _FunctionTraceLogger(\
-	__FUNCTION__, cmb::log4vendor_tracer::_get_file_name(__FILE__), __LINE__)
-
- /*!
- * @brief 类似于 LOG4VTM_FUNCTION(),除外还添加一个入参用于打印返回值,注意该入参的生命周期为整个函数内!!
- * @param[in]: pValue - 仅支持传入 int* 或 DWORD* 类型,在日志中会打印指针所存储的值
- */
-#define TRACE4VTM_FUNCTION(pValue) cmb::log4vendor_tracer _FunctionTraceLogger(\
-	__FUNCTION__, cmb::log4vendor_tracer::_get_file_name(__FILE__), __LINE__, (pValue))
-
-
-namespace cmb {
-
-	struct log_init_config 
-	{
-		short log_type;       /*见上面 CMB_LOG_TYPE_FILE 等定义*/
-		short log_level;      /*见上面 CMB_LOG_TRACE 等定义*/
-		vtm_string dev_name;  /*硬件名称,用于作为子目录的区分*/
-		vtm_string  log_dir;  /*在 log_type 包含 CMB_LOG_TYPE_FILE 时,该参数才有效,用于记录日志的目录*/
-
-		log_init_config()
-			:log_type(CMB_LOG_TYPE_FILE)
-			,log_level(CMB_LOG_TRACE)
-			,dev_name(LOG4VTM_TEXT("VTM")),log_dir(LOG4VTM_TEXT("")){}
-	};
-
-	class LOG4VENDOR_API log4vendor
-	{
-	public:
-
-		static log4vendor* instance();
-
-		 /*!
-		 * @brief 在调用打印日志的相关宏时,请先调用此函数进行初始化,否则将不会打印任何形式的日志内容
-		 *
-		 * @param[in]  
-		 *		config: 日志初始化的配置参数
-		 *		ret_msg: 防止传入的参数有误,在必要的时候记录错误信息,供上层打印排查
-		 *		
-		 *	如传入的参数依次为:"PinPad", CMB_LOG_TYPE_FILE|CMB_LOG_TYPE_CONSOLE, "C:\\rvc\\dbg"
-		 *  那么将会日志记在 "C:\\rvc\\dbg\\PinPad\\{YYYYMMDD}.log" 内,并将支持控制台输出
-		 *		
-		 */
-		static void init(const log_init_config& config, vtm_string& ret_msg);
-
-		virtual void log(int log_level, const vtm_string& text) = 0;
-
-		static std::basic_ostringstream<char>& get_oss();
-		
-		//static std::basic_ostringstream<wchar_t>& get_woss();
-
-#ifdef LIBLOG4VENDOR_EXPORTS
-	public:
-#else
-	private:
-#endif
-		log4vendor() {}
-		virtual ~log4vendor(){}
-	private:
-		log4vendor(const log4vendor& rhs);
-	};
-
-	
-	//////////////////////////////////////////////////////////////////////////
-
-
-
-	class LOG4VENDOR_API log4vendor_tracer
-	{
-	public:
-
-		log4vendor_tracer(const char* message, const char* fileName, int nLine);
-		
-		log4vendor_tracer(const char* message, const char* fileName, int nLine, int* pRet);
-		
-		log4vendor_tracer(const char* message, const char* fileName, int nLine, unsigned long* pRet);
-		
-		~log4vendor_tracer();
-
-
-		static const char* _get_file_name(const char* file_path);
-
-	private:
-		
-		log4vendor_tracer (log4vendor_tracer const &);
-		log4vendor_tracer & operator = (log4vendor_tracer const &);
-
-		const char* m_pszMes;
-		const char* m_pszFileN;
-		int m_nLine;
-
-		int* m_pnRet;
-		unsigned long* m_pDwRet;
-		int* m_pfRet;
-		int m_retType;
-	};
-}
-
-#endif //_VTM_LOG4VENDOR_H_

+ 45 - 19
DevAdapter/self/liblog4vendor/mutex.cpp

@@ -2,24 +2,50 @@
 
 namespace cmb {
 
-	mutex::mutex()
-	{
-		::InitializeCriticalSection(&csection_);
-	}
-
-	mutex::~mutex()
-	{
-		::DeleteCriticalSection(&csection_);
-	}
-
-	void mutex::lock()
-	{
-		::EnterCriticalSection(&csection_);
-	}
-
-	void mutex::unlock()
-	{
-		::LeaveCriticalSection(&csection_);
-	}
+#if defined(_MSC_VER)
+
+    mutex::mutex()
+    {
+        ::InitializeCriticalSection(&csection_);
+    }
+
+    mutex::~mutex()
+    {
+        ::DeleteCriticalSection(&csection_);
+    }
+
+    void mutex::lock()
+    {
+        ::EnterCriticalSection(&csection_);
+    }
+
+    void mutex::unlock()
+    {
+        ::LeaveCriticalSection(&csection_);
+    }
+
+#elif defined(__GNUC__)
+
+    mutex::mutex()
+    {
+        pthread_mutex_init(&mutx_, NULL);
+    }
+
+    mutex::~mutex()
+    {
+        pthread_mutex_destroy(&mutx_);
+    }
+
+    void mutex::lock()
+    {
+        pthread_mutex_lock(&mutx_);
+    }
+
+    void mutex::unlock()
+    {
+        pthread_mutex_unlock(&mutx_);
+    }
+
+#endif
 
 }

+ 10 - 2
DevAdapter/self/liblog4vendor/mutex.h

@@ -1,7 +1,13 @@
+#ifndef RVC_VENDOR_MUTEX_H_
+#define RVC_VENDOR_MUTEX_H_
+
 #pragma once
 
+#ifdef _WIN32
 #include <Windows.h>
-
+#else
+#include <pthread.h>
+#endif //_WIN32
 
 namespace cmb {
 
@@ -64,4 +70,6 @@ namespace cmb {
 		bool owns_;
 	};
 
-}
+}
+
+#endif // RVC_VENDOR_MUTEX_H_

+ 12 - 0
DevAdapter/self/liblog4vendor/test/CMakeLists.txt

@@ -0,0 +1,12 @@
+find_package(Threads)
+
+set(srcs test4log.cpp)
+
+add_executable(test4log ${srcs})
+
+target_link_libraries(test4log log4vendor ${CMAKE_THREAD_LIBS_INIT})
+
+target_include_directories(test4log PRIVATE ${DEVADAPTER_CURRENT_INCLUDES_DIR})
+target_include_directories(test4log PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/..")
+
+rvc_dev_target_install(test4log)

+ 109 - 63
DevAdapter/self/liblog4vendor/test/test4log.cpp

@@ -1,9 +1,15 @@
 // test4log.cpp : 定义控制台应用程序的入口点。
 //
 
+#if defined(_MSC_VER)
 #include "stdafx.h"
+#else
+#define WINAPI
+#endif //_MSC_VER
+
 #include <assert.h>
 #include <time.h>
+#include <thread>
 #include "log4vendor.h"
 #include <iostream>
 
@@ -50,49 +56,61 @@ void logInitize_FileRecord()
 {
 	std::string err_msg;
 	cmb::log_init_config config;
-	config.dev_name =_T("PinPad");
+	config.dev_name =("PinPad");
 	config.log_type = CMB_LOG_TYPE_FILE;
 	config.log_level = CMB_LOG_LEVEL_ALL;
-	config.log_dir =_T("C:\\rvc\\dbg\\");
+#if defined(_MSC_VER)
+	config.log_dir = ("C:\\rvc\\dbg\\");
+#else
+	config.log_dir = ("/opt/rvc/dbg/");
+#endif //_MSC_VER
 
 	cmb::log4vendor::init(config, err_msg);
 	assert(err_msg.empty());
 
-	LOG4VTM(TRACE,_T("This is first TRACE type message."));
-	LOG4VTM(INFO,_T("This is first INFO type message."));
-	LOG4VTM(WARN,_T("This is first WARN type message."));
-	LOG4VTM(ERROR,_T("This is first ERROR type message."));
-	LOG4VTM(FATAL,_T("This is first FATAL type message."));
+	LOG4VTM(TRACE,("This is first TRACE type message."));
+	LOG4VTM(INFO,("This is first INFO type message."));
+	LOG4VTM(WARN,("This is first WARN type message."));
+	LOG4VTM(ERROR,("This is first ERROR type message."));
+	LOG4VTM(FATAL,("This is first FATAL type message."));
 }
 
 void logInitize_Console()
 {
 	std::string err_msg;
 	cmb::log_init_config config;
-	config.dev_name =_T("PinPad");
+	config.dev_name =("PinPad");
 	config.log_type = CMB_LOG_TYPE_FILE | CMB_LOG_TYPE_CONSOLE;
 	config.log_level = CMB_LOG_LEVEL_ALL;
-	config.log_dir =_T("C:\\rvc\\dbg\\");
+#if defined(_MSC_VER)
+    config.log_dir = ("C:\\rvc\\dbg\\");
+#else
+    config.log_dir = ("/opt/rvc/dbg/");
+#endif //_MSC_VER
 
 	cmb::log4vendor::init(config, err_msg);
 	std::cout << err_msg << std::endl;
 	assert(err_msg.empty());
 
-	LOG4VTM(TRACE,_T("This is first TRACE type message."));
-	LOG4VTM(INFO,_T("This is first INFO type message."));
-	LOG4VTM(WARN,_T("This is first WARN type message."));
-	LOG4VTM(ERROR,_T("This is first ERROR type message."));
-	LOG4VTM(FATAL,_T("This is first FATAL type message."));
+	LOG4VTM(TRACE,("This is first TRACE type message."));
+	LOG4VTM(INFO,("This is first INFO type message."));
+	LOG4VTM(WARN,("This is first WARN type message."));
+	LOG4VTM(ERROR,("This is first ERROR type message."));
+	LOG4VTM(FATAL,("This is first FATAL type message."));
 }
 
 void logInitize_SupportDirPathWithoutSlash()
 {
 	std::string err_msg;
 	cmb::log_init_config config;
-	config.dev_name =_T("PinPad");
+	config.dev_name =("PinPad");
 	config.log_type = CMB_LOG_TYPE_FILE;
 	config.log_level = CMB_LOG_LEVEL_ALL;
-	config.log_dir =_T("C:\\rvc\\dbg");
+#if defined(_MSC_VER)
+    config.log_dir = ("C:\\rvc\\dbg\\");
+#else
+    config.log_dir = ("/opt/rvc/dbg/");
+#endif //_MSC_VER
 
 	cmb::log4vendor::init(config, err_msg);
 	assert(err_msg.empty());
@@ -102,22 +120,30 @@ void logInitize_SupportDiffLogLevel_ERROR()
 {
 	std::string err_msg;
 	cmb::log_init_config config;
-	config.dev_name =_T("PinPad");
+	config.dev_name =("PinPad");
 	config.log_type = CMB_LOG_TYPE_FILE;
 	config.log_level = CMB_LOG_LEVEL_ERROR;
-	config.log_dir =_T("C:\\rvc\\dbg\\");
+#if defined(_MSC_VER)
+    config.log_dir = ("C:\\rvc\\dbg\\");
+#else
+    config.log_dir = ("/opt/rvc/dbg/");
+#endif //_MSC_VER
 
 	cmb::log4vendor::init(config, err_msg);
 	assert(err_msg.empty());
 
-	LOG4VTM(TRACE,_T("The TRACE type message would not record!"));
-	LOG4VTM(INFO,_T("The INFO type message would not record!"));
-	LOG4VTM(WARN,_T("The WARN type message would not record!"));
-	LOG4VTM(ERROR,_T("This is first ERROR type message."));
-	LOG4VTM(FATAL,_T("This is first FATAL type message."));
+	LOG4VTM(TRACE,("The TRACE type message would not record!"));
+	LOG4VTM(INFO,("The INFO type message would not record!"));
+	LOG4VTM(WARN,("The WARN type message would not record!"));
+	LOG4VTM(ERROR,("This is first ERROR type message."));
+	LOG4VTM(FATAL,("This is first FATAL type message."));
 }
 
+#if defined(_MSC_VER)
 #include <process.h>
+#else
+#include <pthread.h>
+#endif //_MSC_VER
 
 #define random(x) (rand()%x)
 int get_random(int reft, int right)
@@ -129,11 +155,13 @@ int get_random(int reft, int right)
 	return c;
 }
 
-UINT WINAPI thread1(LPVOID param)
+void thread1(int param)
 {
-	int i = (int)param;
-	TRACE4VTM_FUNCTION(&i);
-	LOG4VTM(INFO,_T("current thread: ") << GetCurrentThreadId());
+#if defined(_MSC_VER)
+	LOG4VTM(INFO, ("current thread: ") << GetCurrentThreadId());
+#else
+	LOG4VTM(INFO, ("current thread: ") << (int)pthread_self());
+#endif //_MSC_VER
 	const int times = 3000;
 	int count = 0;
 	do 
@@ -141,90 +169,109 @@ UINT WINAPI thread1(LPVOID param)
 		const int nInterval = get_random(0, 3000);
 		const int nLevel = nInterval % 6;
 		if(nLevel == 0) {
-			LOG4VTM(ERROR,_T("this is a ERROR log, times: ") << count);
+			LOG4VTM(ERROR,("this is a ERROR log, times: ") << count);
 		} else if(nLevel == 1) {
-			LOG4VTM(FATAL, _T("this is a FATAL log, times: ") << count);
+			LOG4VTM(FATAL, ("this is a FATAL log, times: ") << count);
 		} else if(nLevel == 2) {
-			LOG4VTM(INFO,_T("this is a INFO log, times: ") << count);
+			LOG4VTM(INFO,("this is a INFO log, times: ") << count);
 		} else if(nLevel == 3) {
-			LOG4VTM(DEBUG,_T("this is a DEBUG log, times: ") << count);
+			LOG4VTM(DEBUG,("this is a DEBUG log, times: ") << count);
 		} else if(nLevel == 4) {
-			LOG4VTM(WARN,_T("this is a WRAN log, times: ") << count);
+			LOG4VTM(WARN,("this is a WRAN log, times: ") << count);
 		} else if(nLevel == 5) {
-			LOG4VTM(TRACE,_T("this is a TRACE log, times: ") << count);
+			LOG4VTM(TRACE,("this is a TRACE log, times: ") << count);
 		}
 		//Sleep(nInterval);
 	} while (++count < times);
-
-	return 0;
 }
 
 void MultiThreadTest()
 {
-	srand((int)time(0));
-	int count = 30;
-	HANDLE handle[30];
-	for(int i=0; i<30; ++i)
-		handle[i] = (HANDLE)_beginthreadex(NULL, 0,thread1, (LPVOID)i, 0, NULL);
-	
-	WaitForMultipleObjects(30, handle, TRUE, INFINITE);
+    srand((int)time(0));
+    int count = 30;
+    std::thread* handle[30];
+	for (int i = 0; i < 30; ++i)
+		handle[i] = new std::thread(thread1, i);
+
+	for (int i = 0; i < 30; ++i) {
+        if (handle[i]->joinable())
+            handle[i]->join();
+		delete handle[i];
+		handle[i] = nullptr;
+	}
 }
 
 void logInitize_SupportDiffLogLevel_OFF()
 {
 	std::string err_msg;
 	cmb::log_init_config config;
-	config.dev_name =_T("PinPad");
+	config.dev_name =("PinPad");
 	config.log_type = CMB_LOG_TYPE_FILE;
 	config.log_level = CMB_LOG_LEVEL_OFF;
-	config.log_dir =_T("C:\\rvc\\dbg\\");
+#if defined(_MSC_VER)
+    config.log_dir = ("C:\\rvc\\dbg\\");
+#else
+    config.log_dir = ("/opt/rvc/dbg/");
+#endif //_MSC_VER
 
 	cmb::log4vendor::init(config, err_msg);
 	assert(err_msg.empty());
 
-	LOG4VTM(TRACE,_T("The TRACE type message would not record!"));
-	LOG4VTM(INFO,_T("The INFO type message would not record!"));
-	LOG4VTM(WARN,_T("The WARN type message would not record!"));
-	LOG4VTM(ERROR,_T("The ERROR type message would not record!"));
-	LOG4VTM(FATAL,_T("The FATAL type message would not record!"));
+	LOG4VTM(TRACE,("The TRACE type message would not record!"));
+	LOG4VTM(INFO,("The INFO type message would not record!"));
+	LOG4VTM(WARN,("The WARN type message would not record!"));
+	LOG4VTM(ERROR,("The ERROR type message would not record!"));
+	LOG4VTM(FATAL,("The FATAL type message would not record!"));
 }
 
+#if defined(_MSC_VER)
 int _tmain(int argc, _TCHAR* argv[])
+#else
+int main(int argc, char* argv[])
+#endif //_MSC_VER
 {
 	std::string err_msg;
 	assert(cmb::log4vendor::instance() != NULL);
 	{
 		cmb::log_init_config config1;
-		config1.dev_name =_T("");
+		config1.dev_name =("");
 		config1.log_type = CMB_LOG_TYPE_FILE;
-		config1.log_dir = _T("C:\\rvc\\dbg\\");
+#if defined(_MSC_VER)
+		config1.log_dir = ("C:\\rvc\\dbg\\");
+#else
+		config1.log_dir = ("/opt/rvc/dbg/");
+#endif //_MSC_VER
 
 		cmb::log4vendor::init(config1, err_msg);
-		LOG4VTM(INFO,_T("This message would not be record with illegal dev name!"));
-		assert(!err_msg.empty() &&_T(""));
+		LOG4VTM(INFO,("This message would not be record with illegal dev name!"));
+		assert(!err_msg.empty() &&(""));
 
 	}
 
 	{
 		cmb::log_init_config config2;
-		config2.dev_name =_T("PinPad");
+		config2.dev_name =("PinPad");
 		config2.log_type = ~(CMB_LOG_TYPE_CONSOLE | CMB_LOG_TYPE_FILE | CMB_LOG_TYPE_SOCKET);
-		config2.log_dir =_T("C:\\rvc\\dbg\\");
+#if defined(_MSC_VER)
+		config2.log_dir = ("C:\\rvc\\dbg\\");
+#else
+		config2.log_dir = ("/opt/rvc/dbg/");
+#endif //_MSC_VER
 		cmb::log4vendor::init(config2, err_msg);
-		LOG4VTM(INFO,_T("This message would not be record with illegal log type!"));
-		assert(!err_msg.empty() &&_T(""));
+		LOG4VTM(INFO,("This message would not be record with illegal log type!"));
+		assert(!err_msg.empty() &&(""));
 	}
 
 
 	{
 		cmb::log_init_config config;
-		config.dev_name =_T("PinPad");
+		config.dev_name =("PinPad");
 		config.log_type = CMB_LOG_TYPE_FILE;
-		config.log_dir =_T("");
+		config.log_dir =("");
 
 		cmb::log4vendor::init(config, err_msg);
-		LOG4VTM(INFO,_T("This message would not be record with illegal dir path !"));
-		assert(!err_msg.empty() &&_T(""));
+		LOG4VTM(INFO,("This message would not be record with illegal dir path !"));
+		assert(!err_msg.empty() &&(""));
 
 	}
 
@@ -251,5 +298,4 @@ int _tmain(int argc, _TCHAR* argv[])
 	MultiThreadTest();
 
 	return 0;
-}
-
+}

+ 22 - 26
Module/include/DevEntityCommBase.hpp

@@ -158,83 +158,79 @@ inline ErrorCodeEnum CDevAdptEntityBase::ExtractVendorLibFullPath(CSimpleStringA
 
 inline void CDevAdptEntityBase::InitializeVendorLogSwitch()
 {
+	LOG_FUNCTION();
 
-	if (!vendorLibInfo.IsValid())
-	{
+	if (!vendorLibInfo.IsValid()) {
 		ExtractVendorLibName();
 	}
 
 	struct VendorLogConfig {
 
-		CSimpleStringA strLevel;
-		CSimpleStringA strType;
-		CSimpleStringA strDllName;
-		CSimpleStringA strLogPath;
+		CSimpleStringA strLevel = "OFF";
+		CSimpleStringA strType = "FILE";
+		CSimpleStringA strDllName = "";
+		CSimpleStringA strLogPath = "";
 
-		void Settle() 
-		{
+		void Settle()  {
 			toolkit_setenv("VENDOR_RECODE_LEVEL", strLevel);
 			toolkit_setenv("VENDOR_RECODE_TYPE", strType);
 			toolkit_setenv("VENDOR_DLL_NAME", strDllName);
 			toolkit_setenv("VENDOR_LOG_PATH", strLogPath);
 		}
 
-	} stLogConfig = { "OFF" "FILE", vendorLibInfo.toLibNameString(), ""};
+	} stLogConfig;
+
+	stLogConfig.strDllName = vendorLibInfo.toLibNameString().GetData();
 
 	CSmartPointer<IConfigInfo> centerConfig;
 	GetFunction()->OpenConfig(Config_CenterSetting, centerConfig);
 
 	CSimpleStringA str;
 	centerConfig->ReadConfigValue(GetEntityName(), vendorLibInfo.strVendor, str);
-	if (str.IsNullOrEmpty()) 
-	{
+	if (str.IsNullOrEmpty()) {
+		Dbg("To get all config");
 		centerConfig->ReadConfigValue(GetEntityName(), "All", str);
 	}
+	Dbg("All: %s", str.GetData());
 
-	if (!str.IsNullOrEmpty())
-	{
+	if (!str.IsNullOrEmpty()) {
 		stLogConfig.strLevel = str;
 	}
 
-	if (stLogConfig.strLevel.Compare("OFF", true) != 0)
-	{
+	if (stLogConfig.strLevel.Compare("OFF", true) != 0) {
 		CSystemStaticInfo sysInfo;
 		GetFunction()->GetSystemStaticInfo(sysInfo);
 
 		CSimpleStringA strWhiteNameSheet;
 		centerConfig->ReadConfigValue(GetEntityName(), "AllowTerminals", strWhiteNameSheet);
-		if (!strWhiteNameSheet.IsNullOrEmpty()) 
-		{
+		Dbg("AllowTerminals: %s", strWhiteNameSheet.GetData());
+		if (!strWhiteNameSheet.IsNullOrEmpty())  {
 			bool bWhiteNameSheet = false;
 			
 			CAutoArray<CSimpleStringA> arrayWhiteNameSheet = strWhiteNameSheet.Split(',');
-			for (int i = 0; i < arrayWhiteNameSheet.GetCount(); i++) 
-			{
+			for (int i = 0; i < arrayWhiteNameSheet.GetCount(); i++)  {
 				std::regex pattern(arrayWhiteNameSheet[i]);
-				if (std::regex_match(sysInfo.strTerminalID.GetData(), pattern)) 
-				{
+				if (std::regex_match(sysInfo.strTerminalID.GetData(), pattern))  {
 					bWhiteNameSheet = true;
 					break;
 				}
 			}
 
 			//if this terminal is not at WhiteNameSheet,set level with "OFF".
-			if (!bWhiteNameSheet) 
-			{
+			if (!bWhiteNameSheet) {
 				stLogConfig.strLevel = "OFF";
 			}
 		}
 	}
 
-	if (stLogConfig.strLevel.Compare("OFF", true) != 0) 
-	{
+	if (stLogConfig.strLevel.Compare("OFF", true) != 0) {
 		str.Clear();
 		centerConfig->ReadConfigValue(GetEntityName(), "Type", str);
 		if (!str.IsNullOrEmpty())
 			stLogConfig.strType = str;
 
-		CSimpleStringA strDbgPath;
 		GetFunction()->GetPath("Dbg", stLogConfig.strLogPath);
+		Dbg("Dbg: %s", stLogConfig.strLogPath.GetData());
 		stLogConfig.Settle();
 	}
 }

+ 2 - 4
Module/mod_pinpad/PinPadFSM.cpp

@@ -445,11 +445,9 @@ int CPinPadFSM::Initial()
 	do
 	{
 		Dbg("dodo");
-		if (!m_hDevHelper)
-		{
+		if (!m_hDevHelper) {
 			eErrCode = m_hDevHelper.CreateDevAdptObject();
-			if(eErrCode != Error_Succeed)
-			{
+			if(eErrCode != Error_Succeed) {
 				Dbg("create pinpad module failed %s", SpStrError(eErrCode));
 				LogWarn(Severity_Middle, eErrDev, AlarmDECToBusiness(MEC_DEV_OBJECT_CREATE_FAILED), "Initial:CreateDevComponent");
 				initTries++;