• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022 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 #include "app_event_log_cleaner.h"
16 
17 #include <algorithm>
18 #include <cerrno>
19 #include <cmath>
20 
21 #include "file_util.h"
22 #include "hilog/log.h"
23 
24 namespace OHOS {
25 namespace HiviewDFX {
26 namespace {
27 const HiLogLabel LABEL = { LOG_CORE, 0xD002D07, "HiAppEvent_LogCleaner" };
28 }
GetFilesSize()29 uint64_t AppEventLogCleaner::GetFilesSize()
30 {
31     return FileUtil::GetDirSize(path_);
32 }
33 
ClearSpace(uint64_t curSize,uint64_t maxSize)34 uint64_t AppEventLogCleaner::ClearSpace(uint64_t curSize, uint64_t maxSize)
35 {
36     HiLog::Info(LABEL, "start to clear the space occupied by log files");
37     std::vector<std::string> files;
38     FileUtil::GetDirFiles(path_, files);
39 
40     // delete log files one by one based on the timestamp order of the file name
41     sort(files.begin(), files.end());
42 
43     uint64_t nowSize = curSize;
44     while (!files.empty() && nowSize > maxSize) {
45         std::string delFile = files[0];
46         files.erase(files.begin());
47         if (!FileUtil::IsFileExists(delFile)) {
48             HiLog::Error(LABEL, "failed to access the log file, errno=%{public}d", errno);
49             continue;
50         }
51         uint64_t delFileSize = FileUtil::GetFileSize(delFile);
52         if (!FileUtil::RemoveFile(delFile)) {
53             HiLog::Error(LABEL, "failed to remove the log file, errno=%{public}d", errno);
54             continue;
55         }
56         nowSize -= std::min(delFileSize, nowSize);
57     }
58     return nowSize;
59 }
60 
ClearData()61 void AppEventLogCleaner::ClearData()
62 {
63     HiLog::Info(LABEL, "start to clear the log data");
64     if (FileUtil::IsFileExists(path_) && !FileUtil::ForceRemoveDirectory(path_)) {
65         HiLog::Error(LABEL, "failed to clear the log data, errno=%{public}d", errno);
66     }
67 }
68 } // namespace HiviewDFX
69 } // namespace OHOS
70