1 /*
2  * Copyright (c) 2023 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 <fstream>
17 
18 #include "decorator.h"
19 
20 namespace OHOS {
21 namespace HiviewDFX {
22 namespace UCollectUtil {
UpdateStatInfo(uint64_t startTime,uint64_t endTime,const std::string & funcName,bool isCallSucc)23 void StatInfoWrapper::UpdateStatInfo(uint64_t startTime, uint64_t endTime, const std::string& funcName, bool isCallSucc)
24 {
25     std::lock_guard<std::mutex> lock(mutex_);
26     uint64_t latency = (endTime - startTime) > 0 ? (endTime - startTime) : 0;
27     if (statInfos_.find(funcName) == statInfos_.end()) {
28         StatInfo statInfo = {
29             .name = funcName,
30             .totalCall = 1,
31             .failCall = isCallSucc ? 0 : 1,
32             .avgLatency = latency,
33             .maxLatency = latency,
34             .totalTimeSpend = latency,
35         };
36         statInfos_.insert(std::make_pair(funcName, statInfo));
37         return;
38     }
39 
40     StatInfo& statInfo = statInfos_[funcName];
41     statInfo.totalCall += 1;
42     statInfo.failCall += isCallSucc ? 0 : 1;
43     statInfo.totalTimeSpend += latency;
44     statInfo.maxLatency = statInfo.maxLatency < latency ? latency : statInfo.maxLatency;
45     if (statInfo.totalCall > 0) {
46         statInfo.avgLatency = statInfo.totalTimeSpend / statInfo.totalCall;
47     }
48 }
49 
GetStatInfo()50 std::map<std::string, StatInfo> StatInfoWrapper::GetStatInfo()
51 {
52     std::lock_guard<std::mutex> lock(mutex_);
53     return statInfos_;
54 }
55 
ResetStatInfo()56 void StatInfoWrapper::ResetStatInfo()
57 {
58     std::lock_guard<std::mutex> lock(mutex_);
59     statInfos_.clear();
60 }
61 
WriteLinesToFile(const std::vector<std::string> & stats,bool addBlankLine)62 void UCDecorator::WriteLinesToFile(const std::vector<std::string>& stats, bool addBlankLine)
63 {
64     std::ofstream statFilesStream;
65     statFilesStream.open(UC_STAT_LOG_PATH, std::ios::app);
66     if (!statFilesStream.is_open()) {
67         return;
68     }
69     for (const auto& record : stats) {
70         statFilesStream << record << std::endl;
71     }
72     if (addBlankLine) {
73         statFilesStream << std::endl; // write a blank line to separate content
74     }
75     statFilesStream.close();
76 }
77 } // namespace UCollectUtil
78 } // namespace HiviewDFX
79 } // namespace OHOS
80