1 /*
2  * Copyright (C) 2021 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "nstackx_log.h"
17 
18 #include "securec.h"
19 #include "nstackx_error.h"
20 #define TAG "nStackXLog"
21 static uint32_t g_logLevel = NSTACKX_LOG_LEVEL_INFO;
22 
23 #ifdef BUILD_FOR_WINDOWS
DefaultLogImpl(const char * tag,uint32_t level,const char * format,va_list args)24 static void DefaultLogImpl(const char *tag, uint32_t level, const char *format, va_list args)
25 {
26     SYSTEMTIME st = {0};
27 
28     GetLocalTime(&st);
29     printf("%02u-%02u %02u:%02u:%02u.%03u %d %d %d %s: ", st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond,
30            st.wMilliseconds, GetCurrentProcessId(), GetCurrentThreadId(), level, tag);
31     vprintf(format, args);
32 }
33 
34 static LogImplInternal g_logImpl = DefaultLogImpl;
35 #endif
36 
GetLogLevel(void)37 uint32_t GetLogLevel(void)
38 {
39     return g_logLevel;
40 }
41 
SetLogLevel(uint32_t logLevel)42 void SetLogLevel(uint32_t logLevel)
43 {
44     if (logLevel >= NSTACKX_LOG_LEVEL_END) {
45         return;
46     }
47     g_logLevel = logLevel;
48 }
49 
SetLogImpl(LogImplInternal fn)50 void SetLogImpl(LogImplInternal fn)
51 {
52     if (fn == NULL) {
53         return;
54     }
55 }
56 #ifdef BUILD_FOR_WINDOWS
57 #ifndef NEED_EXPORT_VARIABLE
58 #define NEED_EXPORT_VARIABLE
59 #endif
60 #endif
61 
62 NstakcxLogCallback g_nstackxLogCallBack = PrintfImpl;
63 
SetLogCallback(NstakcxLogCallback logCb)64 int32_t SetLogCallback(NstakcxLogCallback logCb)
65 {
66     if (logCb == NULL) {
67         LOGE(TAG, "log callback is null");
68         return NSTACKX_EINVAL;
69     }
70     if (logCb == g_nstackxLogCallBack) {
71         LOGW(TAG, "log callback is the same");
72         return NSTACKX_EOK;
73     }
74     LOGI(TAG, "log callback changed");
75     g_nstackxLogCallBack = logCb;
76     return NSTACKX_EOK;
77 }
78 
SetDefaultLogCallback(void)79 void SetDefaultLogCallback(void)
80 {
81     g_nstackxLogCallBack = PrintfImpl;
82     return;
83 }