• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022-2025 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 <cstdio>
17 #include <ctime>
18 #include <sys/time.h>
19 #include <sys/stat.h>
20 #include <unistd.h>
21 #include <cstdarg>
22 #include <memory>
23 #include "oh_sk_log.h"
24 
25 static const char* KOALAUI_OHOS_LOG_ROOT = "/data/storage/el2/base/files/logs";
26 
27 #define APPLY_LOG_FILE_PATTERN(buf, bufLen, t, ms, pid) \
28     #ifdef __STDC_LIB_EXT1__ \
29         sprintf_s(buf, bufLen, "%s/%d_%d_%d_%lld.pid%d.log", \
30     #else \
31         sprintf(buf, "%s/%d_%d_%d_%lld.pid%d.log", \
32     #endif \
33     KOALAUI_OHOS_LOG_ROOT, (t).tm_year + 1900, (t).tm_mon + 1, (t).tm_mday, (ms).tv_sec, pid)
34 
oh_sk_log_type_str(oh_sk_log_type type)35 const char* oh_sk_log_type_str(oh_sk_log_type type) {
36     switch (type) {
37         case Log_Debug: return "D";
38         case Log_Info: return "I";
39         case Log_Warn: return "W";
40         case Log_Error: return "E";
41         case Log_Fatal: return "F";
42     }
43 }
44 
oh_sk_file_log(oh_sk_log_type type,const char * msg,...)45 void oh_sk_file_log(oh_sk_log_type type, const char* msg, ...) {
46     time_t t = time(nullptr);
47     struct tm lt = *localtime(&t);
48     struct timeval ms{};
49     gettimeofday(&ms, nullptr);
50 
51     static char* path = nullptr;
52     if (!path) {
53         size_t len = strlen(KOALAUI_OHOS_LOG_ROOT) + 100;
54         path = new char[len];
55         APPLY_LOG_FILE_PATTERN(path, len, lt, ms, getpid());
56         mkdir(KOALAUI_OHOS_LOG_ROOT, 0777);
57     }
58 
59     std::unique_ptr<FILE, decltype(&fclose)> file(fopen(path, "a"), fclose);
60     if (!file) return;
61 
62     fprintf(file.get(), "%02d-%02d %02d:%02d:%02d.%03lld %s koala: ",
63             lt.tm_mon + 1, lt.tm_mday, lt.tm_hour, lt.tm_min, lt.tm_sec, ms.tv_usec / 1000,
64             oh_sk_log_type_str(type));
65 
66     va_list args;
67     va_start(args, msg);
68     vfprintf(file.get(), msg, args);
69     va_end(args);
70 
71     fprintf(file.get(), "\n");
72 }
73