1 /*
2  * Copyright (c) 2024 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 <stdio.h>
17 #include <stdarg.h>
18 
19 #include "securec.h"
20 
21 #include "hnp_base.h"
22 
23 #ifdef __cplusplus
24 extern "C" {
25 #endif
26 
27 #define MAX_LOG_BUFF_LEN 1024
28 
29 const char *g_logLevelName[HNP_LOG_BUTT] = {"INFO", "WARN", "ERROR", "DEBUG"};
30 
31 // 辅助函数,用于替换字符串中的指定子串
ReplaceSubstring(const char * str,const char * from,const char * to)32 static char* ReplaceSubstring(const char* str, const char* from, const char* to)
33 {
34     char* result;
35     int lenStr = strlen(str);
36     int lenFrom = strlen(from);
37     int lenTo = strlen(to);
38     int count = 0;
39     int i;
40     int j;
41 
42     // 计算替换后字符串的长度
43     for (i = 0; str[i] != '\0'; i++) {
44         if (strncmp(&str[i], from, lenFrom) == 0) {
45             count++;
46         }
47     }
48 
49     // 分配新字符串的内存
50     result = (char*)malloc(lenStr + (lenTo - lenFrom) * count + 1);
51     if (result == NULL) {
52         return NULL;
53     }
54 
55     // 复制字符串,替换子串
56     i = 0;
57     j = 0;
58     while (str[i] != '\0') {
59         if (strncmp(&str[i], from, lenFrom) == 0) {
60             if (strcpy_s(&result[j], lenStr + 1 - j, to) != EOK) {
61                 free(result);
62                 return NULL;
63             }
64             j += lenTo;
65             i += lenFrom;
66         } else {
67             result[j++] = str[i++];
68         }
69     }
70     result[j] = '\0';
71     return result;
72 }
73 
HnpLogPrintf(int logLevel,char * module,const char * format,...)74 void HnpLogPrintf(int logLevel, char *module, const char *format, ...)
75 {
76     int ret;
77 
78     char* newFormat = ReplaceSubstring(format, "%{public}", "%");
79     if (newFormat == NULL) {
80         return;
81     }
82 
83     ret = fprintf(stdout, "\n[%s][%s]", g_logLevelName[logLevel], module);
84     if (ret < 0) {
85         free(newFormat);
86         return;
87     }
88 
89     va_list args;
90     va_start(args, format);
91     ret = vfprintf(stdout, newFormat, args);
92     va_end(args);
93     free(newFormat);
94     if (ret < 0) {
95         return;
96     }
97 
98     return;
99 }
100 
101 #ifdef __cplusplus
102 }
103 #endif