• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "log.h"
17 
18 #include <chrono>
19 #include <cstdarg>
20 #include <cstdio>
21 #include <ctime>
22 #include <iomanip>
23 #include <iostream>
24 #include <securec.h>
25 
26 namespace OHOS {
27 namespace AppPackingTool {
28 namespace {
29 const int MAX_LOG_SIZE = 10240;
30 const LOG_LEVEL DEFAULT_LOG_LEVEL = LOG_LEVEL::LOG_LEVEL_INFO;
31 const char LOG_LEVEL_FLAG[5] = {'D', 'I', 'W', 'E', 'F'};
32 const int MS_LEN = 3;
33 }
34 
Log(char * file,char * func,int32_t line,int32_t level,char * format,...)35 void Log(char *file, char *func, int32_t line, int32_t level, char *format, ...)
36 {
37     if (level < DEFAULT_LOG_LEVEL) {
38         return;
39     }
40     auto now = std::chrono::system_clock::now();
41     std::time_t nowT = std::chrono::system_clock::to_time_t(now);
42     std::tm* nowTm = std::localtime(&nowT);
43     std::chrono::milliseconds ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) % 1000;
44 
45     va_list args;
46     va_start(args, format);
47     char buffer[MAX_LOG_SIZE];
48     int len = vsnprintf_s(buffer, sizeof(buffer), sizeof(buffer) - 1, format, args);
49     va_end(args);
50     if (len >= 0 && len < MAX_LOG_SIZE - 1) {
51         std::cout << "[" << std::put_time(nowTm, "%Y-%m-%d %H:%M:%S")
52                 << '.' << std::setfill('0') << std::setw(MS_LEN) << ms.count()
53                 << std::setw(0) << "]"
54                 << "[" << file << ":" << line << "]"
55                 << "[" << func << "]"
56                 << "[" << LOG_LEVEL_FLAG[level] << "] "
57                 << buffer
58                 << std::endl;
59     } else {
60         std::cerr << "Error: Buffer size too small for log message." << std::endl;
61     }
62 }
63 } // namespace AppPackingTool
64 } // namespace OHOS
65