1 /*
2  * Copyright (c) Huawei Technologies Co., Ltd. 2023. All rights reserved.
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 "sp_log.h"
17 
18 #include "securec.h"
19 
20 #ifdef HI_LOG_ENABLE
21 #include "hilog/log.h"
22 #include <string>
23 #include <sstream>
24 #include <iostream>
25 #include <cstring>
26 #include <cstdint>
27 #include <unistd.h>
28 #else
29 #include <cstdio>
30 #endif
31 
32 namespace OHOS {
33 namespace SmartPerf {
34 const int32_t LOG_MAX_LEN = 10000;
35 
SpLogOut(SpLogLevel logLevel, const char *logBuf)36 static void SpLogOut(SpLogLevel logLevel, const char *logBuf)
37 {
38 #ifdef HI_LOG_ENABLE
39     LogLevel hiLogLevel = LOG_INFO;
40     switch (logLevel) {
41         case SP_LOG_DEBUG:
42             hiLogLevel = LOG_DEBUG;
43             break;
44         case SP_LOG_INFO:
45             hiLogLevel = LOG_INFO;
46             break;
47         case SP_LOG_WARN:
48             hiLogLevel = LOG_WARN;
49             break;
50         case SP_LOG_ERROR:
51             hiLogLevel = LOG_ERROR;
52             break;
53         default:
54             break;
55     }
56     (void)HiLogPrint(LOG_CORE, hiLogLevel, LOG_DOMAIN, "SP_daemon", "%{public}s", logBuf);
57 #else
58     switch (logLevel) {
59         case SP_LOG_DEBUG:
60             printf("[D]%s\n", logBuf);
61             break;
62         case SP_LOG_INFO:
63             printf("[I]%s\n", logBuf);
64             break;
65         case SP_LOG_WARN:
66             printf("[W]%s\n", logBuf);
67             break;
68         case SP_LOG_ERROR:
69             printf("[E]%s\n", logBuf);
70             break;
71         default:
72             break;
73     }
74 #endif
75 }
76 
SpLog(SpLogLevel logLevel, const char *fmt, ...)77 void SpLog(SpLogLevel logLevel, const char *fmt, ...)
78 {
79     char logBuf[LOG_MAX_LEN] = {0};
80     int32_t ret = 0;
81     va_list arg;
82     ret = memset_s(&arg, sizeof(va_list), 0, sizeof(va_list));
83     if (ret != 0) {
84         SpLogOut(logLevel, "SP log memset_s error.");
85         return;
86     }
87     va_start(arg, fmt);
88     ret = vsprintf_s(logBuf, sizeof(logBuf), fmt, arg);
89     va_end(arg);
90     if (ret < 0) {
91         SpLogOut(logLevel, "SP log length error.");
92         return;
93     }
94     SpLogOut(logLevel, logBuf);
95 }
96 } // namespace SmartPerf
97 } // namespace OHOS