1 /*
2  * Copyright (c) 2021-2022 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 #include "utils/log.h"
16 
17 #include <cstdint>
18 
StripFormatString(const std::string & prefix,std::string & str)19 [[maybe_unused]] static void StripFormatString(const std::string& prefix, std::string& str)
20 {
21     for (auto pos = str.find(prefix, 0); pos != std::string::npos; pos = str.find(prefix, pos)) {
22         str.erase(pos, prefix.size());
23     }
24 }
25 
26 #if defined(ANDROID_PLATFORM)
27 
28 #include <android/log.h>
29 
30 #define LOG_TAG "NAPI"
31 
32 constexpr int LOG_LEVEL[] = { ANDROID_LOG_DEBUG, ANDROID_LOG_INFO, ANDROID_LOG_WARN, ANDROID_LOG_ERROR,
33     ANDROID_LOG_FATAL };
34 
PrintLog(LogLevel level,const char * fmt,...)35 NAPI_EXPORT void PrintLog(LogLevel level, const char* fmt, ...)
36 {
37     std::string newFmt(fmt);
38     StripFormatString("{public}", newFmt);
39     StripFormatString("{private}", newFmt);
40     va_list args;
41     va_start(args, fmt);
42     __android_log_vprint(LOG_LEVEL[static_cast<int>(level)], LOG_TAG, newFmt.c_str(), args);
43     va_end(args);
44 }
45 
46 #elif defined(MAC_PLATFORM) || defined(WINDOWS_PLATFORM) || defined(IOS_PLATFORM) || defined(LINUX_PLATFORM)
47 
48 #include <securec.h>
49 
50 constexpr uint32_t MAX_BUFFER_SIZE = 4096;
51 
PrintLog(LogLevel level,const char * fmt,...)52 NAPI_EXPORT void PrintLog(LogLevel level, const char* fmt, ...)
53 {
54     std::string newFmt(fmt);
55     StripFormatString("{public}", newFmt);
56     StripFormatString("{private}", newFmt);
57 
58     va_list args;
59     va_start(args, fmt);
60 
61     char buf[MAX_BUFFER_SIZE] = { '\0' };
62     int ret = vsnprintf_s(buf, sizeof(buf), sizeof(buf) - 1, newFmt.c_str(), args);
63     va_end(args);
64     if (ret < 0) {
65         return;
66     }
67 
68     printf("%s\r\n", buf);
69     fflush(stdout);
70 }
71 #endif
72