1 /*
2 * Copyright (C) 2021 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 "hc_log.h"
17
18 #include <inttypes.h>
19 #include "securec.h"
20 #include "hc_types.h"
21
22 #define LOG_PRINT_MAX_LEN 2048
23
24 #ifdef DEV_AUTH_DEBUG_PRINTF
25
26 #include <stdio.h>
27 #include <stdlib.h>
28
29 #define DEV_AUTH_LOG_DEBUG(buf) printf("[D][DEVAUTH]: %s\n", buf)
30 #define DEV_AUTH_LOG_INFO(buf) printf("[I][DEVAUTH]: %s\n", buf)
31 #define DEV_AUTH_LOG_WARN(buf) printf("[W][DEVAUTH]: %s\n", buf)
32 #define DEV_AUTH_LOG_ERROR(buf) printf("[E][DEVAUTH]: %s\n", buf)
33
34 #else
35
36 #include "hilog/log.h"
37
38 #define DEV_AUTH_LOG_DEBUG(buf) HILOG_DEBUG(LOG_CORE, "%{public}s", buf)
39 #define DEV_AUTH_LOG_INFO(buf) HILOG_INFO(LOG_CORE, "%{public}s", buf)
40 #define DEV_AUTH_LOG_WARN(buf) HILOG_WARN(LOG_CORE, "%{public}s", buf)
41 #define DEV_AUTH_LOG_ERROR(buf) HILOG_ERROR(LOG_CORE, "%{public}s", buf)
42
43 #endif
44
45 static __thread int32_t g_logMode = 0;
46 static __thread int64_t g_traceId = 0;
47
DevAuthOutPrint(const char * buf,DevAuthLogLevel level)48 static void DevAuthOutPrint(const char *buf, DevAuthLogLevel level)
49 {
50 switch (level) {
51 case DEV_AUTH_LOG_LEVEL_DEBUG:
52 DEV_AUTH_LOG_DEBUG(buf);
53 break;
54 case DEV_AUTH_LOG_LEVEL_INFO:
55 DEV_AUTH_LOG_INFO(buf);
56 break;
57 case DEV_AUTH_LOG_LEVEL_WARN:
58 DEV_AUTH_LOG_WARN(buf);
59 break;
60 case DEV_AUTH_LOG_LEVEL_ERROR:
61 DEV_AUTH_LOG_ERROR(buf);
62 break;
63 default:
64 break;
65 }
66 }
67
DevAuthLogPrint(DevAuthLogLevel level,const char * funName,const char * fmt,...)68 void DevAuthLogPrint(DevAuthLogLevel level, const char *funName, const char *fmt, ...)
69 {
70 int32_t ulPos = 0;
71 char outStr[LOG_PRINT_MAX_LEN] = {0};
72 int32_t res;
73 if (g_logMode == TRACE_MODE) {
74 res = sprintf_s(outStr, sizeof(outStr), "<%" PRId64 ">%s: ", g_traceId, funName);
75 } else {
76 res = sprintf_s(outStr, sizeof(outStr), "%s: ", funName);
77 }
78 if (res < 0) {
79 return;
80 }
81 ulPos = (int32_t)HcStrlen(outStr);
82 va_list arg;
83 va_start(arg, fmt);
84 res = vsprintf_s(&outStr[ulPos], sizeof(outStr) - ulPos, fmt, arg);
85 va_end(arg);
86 if (res < 0) {
87 return;
88 }
89 DevAuthOutPrint(outStr, level);
90 }
91
SetLogMode(LogMode mode)92 void SetLogMode(LogMode mode)
93 {
94 g_logMode = mode;
95 g_traceId = 0;
96 }
97
SetTraceId(int64_t traceId)98 void SetTraceId(int64_t traceId)
99 {
100 g_traceId = traceId;
101 }
102