1/*
2 * Copyright (c) 2021-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#ifndef COMMUNICATIONNETSTACK_NETSTACK_LOG
17#define COMMUNICATIONNETSTACK_NETSTACK_LOG
18
19#include <cstring>
20#include <string>
21
22#define MAKE_FILE_NAME strrchr(__FILE__, '/') + 1
23
24#if !defined(_WIN32) && !defined(__APPLE__)
25
26#define LOG_DOMAIN 0xD0015B0
27
28#define LOG_TAG "NETSTACK"
29
30#include "hilog/log.h"
31
32#define NETSTACK_HILOG_PRINT(Level, fmt, ...) \
33    (void)HILOG_##Level(LOG_CORE, "[%{public}s:%{public}d] " fmt, MAKE_FILE_NAME, __LINE__, ##__VA_ARGS__)
34
35#define NETSTACK_CORE_HILOG_PRINT(Level, fmt, ...) \
36    (void)HILOG_##Level(LOG_CORE, fmt, ##__VA_ARGS__)
37
38#else
39
40#include "securec.h"
41#include <cstdarg>
42#include <cstdio>
43
44static constexpr uint32_t NETSTACK_MAX_BUFFER_SIZE = 4096;
45
46static void NetStackStripFormatString(const std::string &prefix, std::string &str)
47{
48    for (auto pos = str.find(prefix, 0); pos != std::string::npos; pos = str.find(prefix, pos)) {
49        str.erase(pos, prefix.size());
50    }
51}
52
53static void NetStackPrintLog(const char *fmt, ...)
54{
55    std::string newFmt(fmt);
56    NetStackStripFormatString("{public}", newFmt);
57    NetStackStripFormatString("{private}", newFmt);
58
59    va_list args;
60    va_start(args, fmt);
61
62    char buf[NETSTACK_MAX_BUFFER_SIZE] = {0};
63    int ret = vsnprintf_s(buf, sizeof(buf), sizeof(buf) - 1, newFmt.c_str(), args);
64    if (ret < 0) {
65        va_end(args);
66        return;
67    }
68    va_end(args);
69
70    printf("%s\r\n", buf);
71    fflush(stdout);
72}
73
74#define NETSTACK_HILOG_PRINT(Level, fmt, ...) \
75    NetStackPrintLog("NETSTACK %s [%s:%d] " fmt, #Level, MAKE_FILE_NAME, __LINE__, ##__VA_ARGS__)
76
77#define NETSTACK_CORE_HILOG_PRINT(Level, fmt, ...) NetStackPrintLog("NETSTACK %s " fmt, #Level, ##__VA_ARGS__)
78
79#endif /* !defined(_WIN32) && !defined(__APPLE__) */
80
81#define NETSTACK_LOGE(fmt, ...) NETSTACK_HILOG_PRINT(ERROR, fmt, ##__VA_ARGS__)
82
83#define NETSTACK_LOGI(fmt, ...) NETSTACK_HILOG_PRINT(INFO, fmt, ##__VA_ARGS__)
84
85#define NETSTACK_LOGD(fmt, ...) NETSTACK_HILOG_PRINT(DEBUG, fmt, ##__VA_ARGS__)
86
87#define NETSTACK_CORE_LOGI(fmt, ...) NETSTACK_CORE_HILOG_PRINT(INFO, fmt, ##__VA_ARGS__)
88
89#endif /* COMMUNICATIONNETSTACK_NETSTACK_LOG */
90