1 /*
2 * Copyright (c) 2023 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 "log.h"
17 #if defined(ANDROID_PLATFORM)
18 #include <android/log.h>
19 #endif
20
21 #if defined(IOS_PLATFORM)
22 #include <securec.h>
23 #import <os/log.h>
24 #endif
25
26 namespace OHOS::HiviewDFX::Hilog::Platform {
StripFormatString(const std::string & prefix,std::string & str)27 [[maybe_unused]] static void StripFormatString(const std::string& prefix, std::string& str)
28 {
29 for (auto pos = str.find(prefix, 0); pos != std::string::npos; pos = str.find(prefix, pos)) {
30 str.erase(pos, prefix.size());
31 }
32 }
33
LogPrint(LogLevel level,const char * fmt,...)34 void LogPrint(LogLevel level, const char* fmt, ...)
35 {
36 va_list args;
37 va_start(args, fmt);
38 LogPrint(level, fmt, args);
39 va_end(args);
40 }
41
42 #if defined(ANDROID_PLATFORM)
43 constexpr int32_t LOG_LEVEL[] = { ANDROID_LOG_DEBUG, ANDROID_LOG_INFO, ANDROID_LOG_WARN, ANDROID_LOG_ERROR,
44 ANDROID_LOG_FATAL };
45
LogPrint(LogLevel level,const char * fmt,va_list args)46 void LogPrint(LogLevel level, const char* fmt, va_list args)
47 {
48 std::string newFmt(fmt);
49 StripFormatString("{public}", newFmt);
50 StripFormatString("{private}", newFmt);
51 __android_log_vprint(LOG_LEVEL[static_cast<int>(level)], DFX_PLATFORM_LOG_TAG, newFmt.c_str(), args);
52 }
53 #endif
54
55 #if defined(IOS_PLATFORM)
56 constexpr uint32_t MAX_BUFFER_SIZE = 4096;
57 constexpr os_log_type_t LOG_TYPE[] = {OS_LOG_TYPE_DEBUG, OS_LOG_TYPE_INFO, OS_LOG_TYPE_DEFAULT, OS_LOG_TYPE_ERROR,
58 OS_LOG_TYPE_FAULT};
59 constexpr const char* LOG_TYPE_NAME[] = { "DEBUG", "INFO", "WARNING", "ERROR", "FATAL" };
60
LogPrint(LogLevel level,const char * fmt,va_list args)61 void LogPrint(LogLevel level, const char* fmt, va_list args)
62 {
63 std::string newFmt(fmt);
64 StripFormatString("{public}", newFmt);
65 StripFormatString("{private}", newFmt);
66 char buf[MAX_BUFFER_SIZE] = { '\0' };
67 int ret = vsnprintf_s(buf, sizeof(buf), sizeof(buf) - 1, newFmt.c_str(), args);
68 if (ret < 0) {
69 return;
70 }
71 os_log_type_t logType = LOG_TYPE[static_cast<int>(level)];
72 const char* levelName = LOG_TYPE_NAME[static_cast<int>(level)];
73 os_log_t log = os_log_create(DFX_PLATFORM_LOG_TAG, levelName);
74 os_log(log, "[%{public}s] %{public}s", levelName, buf);
75 }
76 #endif
77 } // namespace OHOS::HiviewDFX::Hilog::Platform