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