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 #include "console.h"
16
17 #include <chrono>
18 #include <vector>
19 #include "log.h"
20
21 namespace OHOS::JsSysModule {
22 using namespace Commonlibrary::Concurrent::Common;
23
24 thread_local std::map<std::string, int64_t> Console::timerMap;
25 thread_local std::map<std::string, uint32_t> Console::counterMap;
26 thread_local std::string Console::groupIndent;
27 constexpr size_t GROUPINDETATIONWIDTH = 2; // 2 : indentation
28 constexpr uint32_t SECOND = 1000;
29 constexpr uint32_t MINUTE = 60 * SECOND;
30 constexpr uint32_t HOUR = 60 * MINUTE;
31
32 std::map<std::string, std::string> tableChars = {
33 {"middleMiddle", "─"},
34 {"rowMiddle", "┼"},
35 {"topRight", "┐"},
36 {"topLeft", "┌"},
37 {"leftMiddle", "├"},
38 {"topMiddle", "┬"},
39 {"bottomRight", "┘"},
40 {"bottomLeft", "└"},
41 {"bottomMiddle", "┴"},
42 {"rightMiddle", "┤"},
43 {"left", "│ "},
44 {"right", " │"},
45 {"middle", " │ "},
46 };
47
LogPrint(LogLevel level,const char * content)48 void Console::LogPrint(LogLevel level, const char* content)
49 {
50 switch (level) {
51 case LogLevel::DEBUG:
52 HILOG_DEBUG("%{public}s", content);
53 break;
54 case LogLevel::INFO:
55 HILOG_INFO("%{public}s", content);
56 break;
57 case LogLevel::WARN:
58 HILOG_WARN("%{public}s", content);
59 break;
60 case LogLevel::ERROR:
61 HILOG_ERROR("%{public}s", content);
62 break;
63 case LogLevel::FATAL:
64 HILOG_FATAL("%{public}s", content);
65 break;
66 default:
67 HILOG_FATAL("Console::LogPrint: this branch is unreachable");
68 }
69 }
70
ParseLogContent(const std::vector<std::string> & params)71 std::string Console::ParseLogContent(const std::vector<std::string>& params)
72 {
73 std::string ret;
74 if (params.empty()) {
75 return ret;
76 }
77 std::string formatStr = params[0];
78 size_t size = params.size();
79 size_t len = formatStr.size();
80 size_t pos = 0;
81 size_t count = 1;
82 for (; pos < len; ++pos) {
83 if (count >= size) {
84 break;
85 }
86 if (formatStr[pos] == '%') {
87 if (pos + 1 >= len) {
88 break;
89 }
90 switch (formatStr[pos + 1]) {
91 case 's':
92 case 'j':
93 case 'd':
94 case 'O':
95 case 'o':
96 case 'i':
97 case 'f':
98 case 'c':
99 ret += params[count++];
100 ++pos;
101 break;
102 case '%':
103 ret += formatStr[pos];
104 ++pos;
105 break;
106 default:
107 ret += formatStr[pos];
108 break;
109 }
110 } else {
111 ret += formatStr[pos];
112 }
113 }
114 if (pos < len) {
115 ret += formatStr.substr(pos, len - pos);
116 }
117 for (; count < size; ++count) {
118 ret += " ";
119 ret += params[count];
120 }
121 return ret;
122 }
123
MakeLogContent(napi_env env,napi_callback_info info,size_t & argc,size_t startIdx,bool format)124 std::string Console::MakeLogContent(napi_env env, napi_callback_info info, size_t& argc, size_t startIdx, bool format)
125 {
126 std::vector<std::string> content;
127 content.reserve(argc);
128 // get argv
129 napi_value* argv = new napi_value[argc];
130 Helper::ObjectScope<napi_value> scope(argv, true);
131 napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
132
133 for (size_t i = startIdx; i < argc; i++) {
134 if (!Helper::NapiHelper::IsString(env, argv[i])) {
135 napi_value buffer;
136 napi_status status = napi_coerce_to_string(env, argv[i], &buffer);
137 if (status != napi_ok) {
138 HILOG_ERROR("Console log failed to convert to string object");
139 continue;
140 }
141 argv[i] = buffer;
142 }
143 std::string stringValue = Helper::NapiHelper::GetPrintString(env, argv[i]);
144 if (stringValue.empty()) {
145 HILOG_ERROR("Console log content must not be null.");
146 continue;
147 }
148 content.emplace_back(stringValue);
149 }
150 if (format) {
151 return ParseLogContent(content);
152 } else {
153 std::string ret;
154 size_t size = content.size();
155 for (size_t i = 0; i < size; ++i) {
156 ret += " ";
157 ret += content[i];
158 }
159 return ret;
160 }
161 }
162
StringRepeat(size_t number,const std::string & tableChars)163 std::string Console::StringRepeat(size_t number, const std::string& tableChars)
164 {
165 std::string divider;
166 size_t length = number;
167 for (size_t i = 0; i < length; i++) {
168 divider += tableChars;
169 }
170 return divider;
171 }
172
173
174 template<LogLevel LEVEL>
ConsoleLog(napi_env env,napi_callback_info info)175 napi_value Console::ConsoleLog(napi_env env, napi_callback_info info)
176 {
177 size_t argc = Helper::NapiHelper::GetCallbackInfoArgc(env, info);
178 if (argc < 1) {
179 return Helper::NapiHelper::GetUndefinedValue(env);
180 }
181 std::string content;
182 content += groupIndent;
183 content += MakeLogContent(env, info, argc, 0); // startInx = 0
184 LogPrint(LEVEL, content.c_str());
185 return Helper::NapiHelper::GetUndefinedValue(env);
186 }
187
GetTimerOrCounterName(napi_env env,napi_callback_info info,size_t argc)188 std::string Console::GetTimerOrCounterName(napi_env env, napi_callback_info info, size_t argc)
189 {
190 if (argc < 1) {
191 return "default";
192 }
193 napi_value* argv = new napi_value[argc];
194 Helper::ObjectScope<napi_value> scope(argv, true);
195 napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
196 if (!Helper::NapiHelper::IsString(env, argv[0])) {
197 napi_value buffer = nullptr;
198 napi_status status = napi_coerce_to_string(env, argv[0], &buffer);
199 if (status != napi_ok) {
200 Helper::ErrorHelper::ThrowError(env, Helper::ErrorHelper::TYPE_ERROR,
201 "Timer or Counter name must be String.");
202 return "";
203 }
204 argv[0] = buffer;
205 }
206 std::string name = Helper::NapiHelper::GetPrintString(env, argv[0]);
207 if (name.empty()) {
208 Helper::ErrorHelper::ThrowError(env, Helper::ErrorHelper::TYPE_ERROR,
209 "Timer or Counter name must be not null.");
210 return "";
211 }
212 return name;
213 }
214
Count(napi_env env,napi_callback_info info)215 napi_value Console::Count(napi_env env, napi_callback_info info)
216 {
217 size_t argc = Helper::NapiHelper::GetCallbackInfoArgc(env, info);
218 std::string counterName = GetTimerOrCounterName(env, info, argc);
219 counterMap[counterName]++;
220 HILOG_INFO("%{public}s%{public}s: %{public}d",
221 groupIndent.c_str(), counterName.c_str(), counterMap[counterName]);
222 return Helper::NapiHelper::GetUndefinedValue(env);
223 }
224
CountReset(napi_env env,napi_callback_info info)225 napi_value Console::CountReset(napi_env env, napi_callback_info info)
226 {
227 size_t argc = Helper::NapiHelper::GetCallbackInfoArgc(env, info);
228 std::string counterName = GetTimerOrCounterName(env, info, argc);
229 if (counterMap.find(counterName) == counterMap.end()) {
230 HILOG_WARN("%{public}sCounter %{public}s doesn't exists, please check Counter Name.",
231 groupIndent.c_str(), counterName.c_str());
232 return Helper::NapiHelper::GetUndefinedValue(env);
233 }
234 counterMap.erase(counterName);
235 return Helper::NapiHelper::GetUndefinedValue(env);
236 }
237
Dir(napi_env env,napi_callback_info info)238 napi_value Console::Dir(napi_env env, napi_callback_info info)
239 {
240 size_t argc = Helper::NapiHelper::GetCallbackInfoArgc(env, info);
241 if (argc < 1) {
242 HILOG_INFO("%{public}sundefined", groupIndent.c_str());
243 return Helper::NapiHelper::GetUndefinedValue(env);
244 }
245 napi_value* argv = new napi_value[argc];
246 Helper::ObjectScope<napi_value> scope(argv, true);
247 napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
248 std::string ctorVal = Helper::NapiHelper::GetConstructorName(env, argv[0]);
249 // JSON.stringify()
250 napi_value globalValue = nullptr;
251 napi_get_global(env, &globalValue);
252 napi_value jsonValue;
253 napi_get_named_property(env, globalValue, "JSON", &jsonValue);
254 napi_value stringifyValue = nullptr;
255 napi_get_named_property(env, jsonValue, "stringify", &stringifyValue);
256 napi_value transValue = nullptr;
257 napi_call_function(env, jsonValue, stringifyValue, 1, &argv[0], &transValue);
258 if (transValue == nullptr) {
259 Helper::ErrorHelper::ThrowError(env, Helper::ErrorHelper::TYPE_ERROR, "Dir content must not be null.");
260 return Helper::NapiHelper::GetUndefinedValue(env);
261 }
262 std::string content = Helper::NapiHelper::GetPrintString(env, transValue);
263 bool functionFlag = Helper::NapiHelper::IsFunction(env, argv[0]);
264 if (!ctorVal.empty() && !functionFlag) {
265 HILOG_INFO("%{public}s%{public}s: %{public}s", groupIndent.c_str(), ctorVal.c_str(), content.c_str());
266 } else if (!ctorVal.empty() && functionFlag) {
267 HILOG_INFO("%{public}s[Function %{public}s]", groupIndent.c_str(), ctorVal.c_str());
268 } else {
269 HILOG_INFO("%{public}s%{public}s", groupIndent.c_str(), content.c_str());
270 }
271 return Helper::NapiHelper::GetUndefinedValue(env);
272 }
273
Group(napi_env env,napi_callback_info info)274 napi_value Console::Group(napi_env env, napi_callback_info info)
275 {
276 size_t argc = Helper::NapiHelper::GetCallbackInfoArgc(env, info);
277 if (argc > 0) {
278 ConsoleLog<LogLevel::INFO>(env, info);
279 }
280 groupIndent += StringRepeat(GROUPINDETATIONWIDTH, " ");
281 return Helper::NapiHelper::GetUndefinedValue(env);
282 }
283
GroupEnd(napi_env env,napi_callback_info info)284 napi_value Console::GroupEnd(napi_env env, napi_callback_info info)
285 {
286 size_t length = groupIndent.size();
287 if (length > GROUPINDETATIONWIDTH) {
288 groupIndent = groupIndent.substr(0, length - GROUPINDETATIONWIDTH);
289 }
290 return Helper::NapiHelper::GetUndefinedValue(env);
291 }
292
ArrayJoin(std::vector<std::string> rowDivider,const std::string & tableChars)293 std::string Console::ArrayJoin(std::vector<std::string> rowDivider, const std::string& tableChars)
294 {
295 size_t size = rowDivider.size();
296 if (size == 0) {
297 return "no rowDivider";
298 }
299 std::string result = rowDivider[0];
300 for (size_t i = 1; i < size; i++) {
301 result += tableChars;
302 result += rowDivider[i];
303 }
304 return result;
305 }
306
RenderHead(napi_env env,napi_value head,std::vector<size_t> columnWidths)307 std::string Console::RenderHead(napi_env env, napi_value head, std::vector<size_t> columnWidths)
308 {
309 std::string result = tableChars["left"];
310 size_t length = columnWidths.size();
311 for (size_t i = 0; i < length; i++) {
312 napi_value element = nullptr;
313 napi_get_element(env, head, i, &element);
314 napi_value string = nullptr;
315 napi_status status = napi_coerce_to_string(env, element, &string);
316 if (status != napi_ok) {
317 Helper::ErrorHelper::ThrowError(env, Helper::ErrorHelper::TYPE_ERROR,
318 "Table elements can't convert to string.");
319 return "";
320 }
321 std::string elemStr = Helper::NapiHelper::GetPrintString(env, string);
322 size_t stringLen = elemStr.size();
323 size_t left = (columnWidths[i] - stringLen) / 2; // 2: half
324 size_t right = columnWidths[i] - stringLen - left;
325 result += StringRepeat(left, " ") + elemStr + StringRepeat(right, " ");
326 if (i != length - 1) {
327 result += tableChars["middle"];
328 }
329 }
330 result += tableChars["right"];
331 return result;
332 }
333
GetStringAndStringWidth(napi_env env,napi_value element,size_t & stringLen)334 std::string Console::GetStringAndStringWidth(napi_env env, napi_value element, size_t& stringLen)
335 {
336 napi_value string = nullptr;
337 napi_status status = napi_coerce_to_string(env, element, &string);
338 if (status != napi_ok) {
339 Helper::ErrorHelper::ThrowError(env, Helper::ErrorHelper::TYPE_ERROR,
340 "GetStringAndStringWidth: can't convert to string.");
341 return "";
342 }
343 std::string result = Helper::NapiHelper::GetPrintString(env, string);
344 napi_valuetype valuetype;
345 napi_typeof(env, element, &valuetype);
346 if (valuetype != napi_undefined) {
347 stringLen = result.size(); // If element type is undefined, length is 0.
348 }
349 return result;
350 }
351
PrintRows(napi_env env,napi_value Rows,std::vector<size_t> columnWidths,size_t indexNum)352 void Console::PrintRows(napi_env env, napi_value Rows, std::vector<size_t> columnWidths, size_t indexNum)
353 {
354 size_t length = columnWidths.size();
355 for (size_t i = 0; i < indexNum; i++) {
356 std::string result = tableChars["left"];
357 for (size_t j = 0; j < length; j++) {
358 napi_value element = nullptr;
359 napi_get_element(env, Rows, j * indexNum + i, &element);
360 size_t stringLen = 0;
361 std::string stringVal = GetStringAndStringWidth(env, element, stringLen);
362 if (stringLen > 0) {
363 size_t left = (columnWidths[j] - stringLen) / 2; // 2: half
364 size_t right = columnWidths[j] - stringLen - left;
365 result += StringRepeat(left, " ") + stringVal + StringRepeat(right, " ");
366 } else {
367 result += StringRepeat(columnWidths[j], " ");
368 }
369 if (j != length - 1) {
370 result += tableChars["middle"];
371 }
372 }
373 result += tableChars["right"];
374 HILOG_INFO("%{public}s%{public}s", groupIndent.c_str(), result.c_str());
375 }
376 }
377
GraphTable(napi_env env,napi_value head,napi_value columns,const size_t & length)378 void Console::GraphTable(napi_env env, napi_value head, napi_value columns, const size_t& length)
379 {
380 uint32_t columnLen = 0;
381 napi_get_array_length(env, head, &columnLen);
382 std::vector<size_t> columnWidths(columnLen);
383 std::vector<std::string> rowDivider(columnLen);
384 // get maxColumnWidths and get rowDivider(------)
385 // get key string length
386 for (size_t i = 0; i < columnLen; i++) {
387 napi_value element = nullptr;
388 napi_get_element(env, head, i, &element);
389 size_t stringLen = 0;
390 GetStringAndStringWidth(env, element, stringLen);
391 columnWidths[i] = stringLen;
392 }
393 // compare key/value string and get max length
394 for (size_t i = 0; i < columnLen; i++) {
395 for (size_t j = 0; j < length; j++) {
396 napi_value element = nullptr;
397 napi_get_element(env, columns, i * length + j, &element);
398 size_t stringLen = 0;
399 GetStringAndStringWidth(env, element, stringLen);
400 columnWidths[i] = columnWidths[i] > stringLen ? columnWidths[i] : stringLen;
401 }
402 rowDivider[i] = StringRepeat(columnWidths[i] + 2, tableChars["middleMiddle"]); // 2: two space
403 }
404 // print head row
405 std::string indexRow1 = tableChars["topLeft"] +
406 ArrayJoin(rowDivider, tableChars["topMiddle"]) +
407 tableChars["topRight"];
408 std::string indexRow2 = RenderHead(env, head, columnWidths);
409 std::string indexRow3 = tableChars["leftMiddle"] +
410 ArrayJoin(rowDivider, tableChars["rowMiddle"]) +
411 tableChars["rightMiddle"];
412 HILOG_INFO("%{public}s%{public}s", groupIndent.c_str(), indexRow1.c_str());
413 HILOG_INFO("%{public}s%{public}s", groupIndent.c_str(), indexRow2.c_str());
414 HILOG_INFO("%{public}s%{public}s", groupIndent.c_str(), indexRow3.c_str());
415 // print value row
416 PrintRows(env, columns, columnWidths, length);
417 // print end row
418 std::string endRow = tableChars["bottomLeft"] +
419 ArrayJoin(rowDivider, tableChars["bottomMiddle"]) +
420 tableChars["bottomRight"];
421 HILOG_INFO("%{public}s%{public}s", groupIndent.c_str(), endRow.c_str());
422 }
423
GetKeyArray(napi_env env,napi_value map)424 napi_value GetKeyArray(napi_env env, napi_value map)
425 {
426 napi_value mapKeys = nullptr;
427 napi_object_get_keys(env, map, &mapKeys);
428 uint32_t maplen = 0;
429 napi_get_array_length(env, mapKeys, &maplen);
430
431 size_t keyLength = maplen + 1;
432 napi_value outputKeysArray = nullptr;
433 napi_create_array_with_length(env, keyLength, &outputKeysArray);
434 // set (index) to array
435 napi_value result = nullptr;
436 napi_create_string_utf8(env, "(index)", NAPI_AUTO_LENGTH, &result);
437 napi_set_element(env, outputKeysArray, 0, result);
438
439 // set Keys to array
440 for (size_t j = 0; j < maplen ; ++j) {
441 napi_value keyNumber = nullptr;
442 napi_get_element(env, mapKeys, j, &keyNumber);
443 napi_set_element(env, outputKeysArray, j + 1, keyNumber); // startkeyIdx = 1
444 }
445 return outputKeysArray;
446 }
447
GetValueArray(napi_env env,napi_value map,const size_t & length,napi_value keyArray)448 napi_value GetValueArray(napi_env env, napi_value map, const size_t& length, napi_value keyArray)
449 {
450 napi_value mapKeys = nullptr;
451 napi_object_get_keys(env, map, &mapKeys);
452 uint32_t maplen = 0;
453 napi_get_array_length(env, mapKeys, &maplen);
454 size_t keyLength = maplen + 1;
455
456 size_t valueLength = keyLength * length;
457 napi_value outputValuesArray = nullptr;
458 napi_create_array_with_length(env, valueLength, &outputValuesArray);
459 // set indexKeyValue
460 size_t valueIdx = 0;
461 for (size_t j = 0; j < length ; ++j) {
462 napi_value keyNumber = nullptr;
463 napi_get_element(env, keyArray, j, &keyNumber);
464 napi_set_element(env, outputValuesArray, valueIdx++, keyNumber);
465 }
466 for (size_t i = 0; i < maplen ; ++i) {
467 napi_value keyNumber = nullptr;
468 napi_get_element(env, mapKeys, i, &keyNumber);
469 char* innerKey = Helper::NapiHelper::GetString(env, keyNumber);
470 if (innerKey == nullptr) {
471 Helper::ErrorHelper::ThrowError(env, Helper::ErrorHelper::TYPE_ERROR,
472 "property key must not be null.");
473 return Helper::NapiHelper::GetUndefinedValue(env);
474 }
475 napi_value valueNumber = nullptr;
476 napi_get_named_property(env, map, innerKey, &valueNumber);
477 Helper::CloseHelp::DeletePointer(innerKey, true);
478 for (size_t j = 0; j < length ; ++j) {
479 napi_value value = nullptr;
480 napi_get_element(env, valueNumber, j, &value);
481 napi_set_element(env, outputValuesArray, valueIdx++, value);
482 }
483 }
484 return outputValuesArray;
485 }
486
SetPrimitive(napi_env env,napi_value map,const size_t & length,napi_value valuesKeyArray,napi_value outputKeysArray,napi_value outputValuesArray)487 void SetPrimitive(napi_env env, napi_value map, const size_t& length, napi_value valuesKeyArray,
488 napi_value outputKeysArray, napi_value outputValuesArray)
489 {
490 napi_value mapKeys = nullptr;
491 napi_object_get_keys(env, map, &mapKeys);
492 uint32_t maplen = 0;
493 napi_get_array_length(env, mapKeys, &maplen);
494 napi_value result = nullptr;
495 napi_create_string_utf8(env, "Values", NAPI_AUTO_LENGTH, &result);
496 napi_set_element(env, outputKeysArray, maplen + 1, result);
497 uint32_t valuesLen = 0;
498 napi_get_array_length(env, valuesKeyArray, &valuesLen);
499 size_t startVal = (maplen + 1) * length;
500 for (size_t j = 0; j < length ; ++j) {
501 napi_value value = nullptr;
502 napi_get_element(env, valuesKeyArray, j, &value);
503 napi_set_element(env, outputValuesArray, startVal + j, value);
504 }
505 }
506
Table(napi_env env,napi_callback_info info)507 napi_value Console::Table(napi_env env, napi_callback_info info)
508 {
509 size_t argc = Helper::NapiHelper::GetCallbackInfoArgc(env, info);
510 if (argc < 1) {
511 return Helper::NapiHelper::GetUndefinedValue(env);
512 }
513 napi_value* argv = new napi_value[argc];
514 Helper::ObjectScope<napi_value> scope(argv, true);
515 napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
516 if (!Helper::NapiHelper::IsObject(env, argv[0])) {
517 ConsoleLog<LogLevel::INFO>(env, info);
518 }
519 napi_value tabularData = argv[0];
520 // map/set object is incomplete, needs add.
521
522 napi_value keyArray = nullptr;
523 napi_object_get_keys(env, tabularData, &keyArray);
524 uint32_t length = 0;
525 napi_get_array_length(env, keyArray, &length);
526 napi_value valuesKeyArray = nullptr;
527 napi_create_array_with_length(env, length, &valuesKeyArray);
528
529 napi_value map = nullptr;
530 napi_create_object(env, &map);
531 bool hasPrimitive = false;
532 bool primitiveInit = false;
533 napi_value keys = nullptr;
534 std::map<std::string, bool> initialMap;
535 for (size_t i = 0; i < length; i++) {
536 // get key
537 napi_value napiNumber = nullptr;
538 napi_get_element(env, keyArray, i, &napiNumber);
539 char* key = Helper::NapiHelper::GetString(env, napiNumber);
540 if (key == nullptr) {
541 Helper::ErrorHelper::ThrowError(env, Helper::ErrorHelper::TYPE_ERROR,
542 "property key must not be null.");
543 return Helper::NapiHelper::GetUndefinedValue(env);
544 }
545 napi_value item = nullptr;
546 napi_get_named_property(env, tabularData, key, &item);
547 Helper::CloseHelp::DeletePointer(key, true);
548 bool isPrimitive = ((item == nullptr) ||
549 (!Helper::NapiHelper::IsObject(env, item) && !Helper::NapiHelper::IsFunction(env, item)));
550 if (isPrimitive) {
551 if (!primitiveInit) {
552 for (size_t j = 0; j < length ; ++j) {
553 napi_value result = nullptr;
554 napi_create_string_utf8(env, "", NAPI_AUTO_LENGTH, &result);
555 napi_set_element(env, valuesKeyArray, j, result);
556 }
557 primitiveInit = true;
558 }
559 hasPrimitive = true;
560 napi_set_element(env, valuesKeyArray, i, item);
561 } else {
562 // get inner keys
563 uint32_t innerLength = 0;
564 napi_object_get_keys(env, item, &keys);
565 napi_get_array_length(env, keys, &innerLength);
566 // set value to array
567 for (size_t j = 0; j < innerLength ; ++j) {
568 napi_value keyNumber = nullptr;
569 napi_get_element(env, keys, j, &keyNumber);
570 char* innerKey = Helper::NapiHelper::GetString(env, keyNumber);
571 if (innerKey == nullptr) {
572 Helper::ErrorHelper::ThrowError(env, Helper::ErrorHelper::TYPE_ERROR,
573 "property key must not be null.");
574 return Helper::NapiHelper::GetUndefinedValue(env);
575 }
576 napi_value innerItem = nullptr;
577 if (isPrimitive) {
578 napi_value result = nullptr;
579 napi_create_string_utf8(env, "", NAPI_AUTO_LENGTH, &result);
580 innerItem = result;
581 } else {
582 napi_get_named_property(env, item, innerKey, &innerItem);
583 }
584 // re-palce(sort) key, value.
585 if (initialMap.find(std::string(innerKey)) == initialMap.end()) {
586 napi_value mapArray = nullptr;
587 napi_create_array_with_length(env, length, &mapArray);
588 napi_set_element(env, mapArray, i, innerItem);
589 napi_set_named_property(env, map, innerKey, mapArray);
590 initialMap[innerKey] = true;
591 } else {
592 napi_value mapArray = nullptr;
593 napi_get_named_property(env, map, innerKey, &mapArray);
594 napi_set_element(env, mapArray, i, innerItem);
595 napi_set_named_property(env, map, innerKey, mapArray);
596 }
597 Helper::CloseHelp::DeletePointer(innerKey, true);
598 }
599 }
600 }
601 // set outputKeysArray
602 napi_value outputKeysArray = GetKeyArray(env, map);
603 // set outputValuesArray
604 napi_value outputValuesArray = GetValueArray(env, map, length, keyArray);
605 // if has Primitive, add new colomn Values
606 if (hasPrimitive) {
607 SetPrimitive(env, map, length, valuesKeyArray, outputKeysArray, outputValuesArray);
608 }
609 GraphTable(env, outputKeysArray, outputValuesArray, length);
610 return Helper::NapiHelper::GetUndefinedValue(env);
611 }
612
PrintTime(std::string timerName,double time,const std::string & log)613 void Console::PrintTime(std::string timerName, double time, const std::string& log)
614 {
615 uint32_t hours = 0;
616 uint32_t minutes = 0;
617 uint32_t seconds = 0;
618 uint32_t ms = time;
619 if (ms >= SECOND) {
620 if (ms >= MINUTE) {
621 if (ms >= HOUR) {
622 hours = ms / HOUR;
623 ms = ms - HOUR * hours;
624 }
625 minutes = ms / MINUTE;
626 ms = ms - MINUTE * minutes;
627 }
628 seconds = ms / SECOND;
629 ms = ms - SECOND * seconds;
630 }
631 if (hours != 0) {
632 HILOG_INFO("%{public}s%{public}s: %{public}d:%{public}.2d:%{public}.2d.%{public}.3d(h:m:s.mm) %{public}s",
633 groupIndent.c_str(), timerName.c_str(), hours, minutes, seconds, ms, log.c_str());
634 return;
635 }
636 if (minutes != 0) {
637 HILOG_INFO("%{public}s%{public}s: %{public}d:%{public}.2d.%{public}.3d(m:s.mm) %{public}s",
638 groupIndent.c_str(), timerName.c_str(), minutes, seconds, ms, log.c_str());
639 return;
640 }
641 if (seconds != 0) {
642 HILOG_INFO("%{public}s%{public}s: %{public}d.%{public}.3ds %{public}s",
643 groupIndent.c_str(), timerName.c_str(), seconds, ms, log.c_str());
644 return;
645 }
646 HILOG_INFO("%{public}s%{public}s: %{public}.3fms %{public}s",
647 groupIndent.c_str(), timerName.c_str(), time, log.c_str());
648 }
649
Time(napi_env env,napi_callback_info info)650 napi_value Console::Time(napi_env env, napi_callback_info info)
651 {
652 size_t argc = Helper::NapiHelper::GetCallbackInfoArgc(env, info);
653 std::string timerName = GetTimerOrCounterName(env, info, argc);
654 if (timerMap.find(timerName) == timerMap.end()) {
655 timerMap[timerName] = std::chrono::duration_cast<std::chrono::microseconds>
656 (std::chrono::high_resolution_clock::now().time_since_epoch()).count();
657 } else {
658 HILOG_WARN("Timer %{public}s already exists, please check Timer Name", timerName.c_str());
659 }
660 return Helper::NapiHelper::GetUndefinedValue(env);
661 }
662
TimeLog(napi_env env,napi_callback_info info)663 napi_value Console::TimeLog(napi_env env, napi_callback_info info)
664 {
665 size_t argc = Helper::NapiHelper::GetCallbackInfoArgc(env, info);
666 std::string timerName = GetTimerOrCounterName(env, info, argc);
667 if (timerMap.find(timerName) != timerMap.end()) {
668 // get time in ms
669 int64_t endTime = std::chrono::duration_cast<std::chrono::microseconds>
670 (std::chrono::high_resolution_clock::now().time_since_epoch()).count();
671 double ms = static_cast<uint64_t>(endTime - timerMap[timerName]) / 1000.0;
672 std::string content = MakeLogContent(env, info, argc, 1, false); // startInx = 1, format = false;
673 PrintTime(timerName, ms, content);
674 } else {
675 HILOG_WARN("%{public}sTimer %{public}s doesn't exists, please check Timer Name.",
676 groupIndent.c_str(), timerName.c_str());
677 }
678 return Helper::NapiHelper::GetUndefinedValue(env);
679 }
680
TimeEnd(napi_env env,napi_callback_info info)681 napi_value Console::TimeEnd(napi_env env, napi_callback_info info)
682 {
683 size_t argc = Helper::NapiHelper::GetCallbackInfoArgc(env, info);
684 std::string timerName = GetTimerOrCounterName(env, info, argc);
685 if (timerMap.find(timerName) != timerMap.end()) {
686 // get time in ms
687 int64_t endTime = std::chrono::duration_cast<std::chrono::microseconds>
688 (std::chrono::high_resolution_clock::now().time_since_epoch()).count();
689 double ms = static_cast<uint64_t>(endTime - timerMap[timerName]) / 1000.0;
690 PrintTime(timerName, ms, "");
691 timerMap.erase(timerName);
692 } else {
693 HILOG_WARN("%{public}sTimer %{public}s doesn't exists, please check Timer Name.",
694 groupIndent.c_str(), timerName.c_str());
695 }
696 return Helper::NapiHelper::GetUndefinedValue(env);
697 }
698
Trace(napi_env env,napi_callback_info info)699 napi_value Console::Trace(napi_env env, napi_callback_info info)
700 {
701 size_t argc = Helper::NapiHelper::GetCallbackInfoArgc(env, info);
702 std::string content;
703 if (argc > 0) {
704 content = MakeLogContent(env, info, argc, 0); // startInx = 0
705 }
706 HILOG_INFO("%{public}sTrace: %{public}s", groupIndent.c_str(), content.c_str());
707 std::string stack;
708 napi_get_stack_trace(env, stack);
709 std::string tempStr = "";
710 for (size_t i = 0; i < stack.length(); i++) {
711 if (stack[i] == '\n') {
712 HILOG_INFO("%{public}s%{public}s", groupIndent.c_str(), tempStr.c_str());
713 tempStr = "";
714 } else {
715 tempStr += stack[i];
716 }
717 }
718 return Helper::NapiHelper::GetUndefinedValue(env);
719 }
720
Assert(napi_env env,napi_callback_info info)721 napi_value Console::Assert(napi_env env, napi_callback_info info)
722 {
723 // 1. check args
724 size_t argc = Helper::NapiHelper::GetCallbackInfoArgc(env, info);
725 if (argc < 1) {
726 HILOG_ERROR("%{public}sAssertion failed", groupIndent.c_str());
727 return Helper::NapiHelper::GetUndefinedValue(env);
728 }
729 napi_value* argv = new napi_value[argc];
730 Helper::ObjectScope<napi_value> scope(argv, true);
731 napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
732
733 if (Helper::NapiHelper::GetBooleanValue(env, argv[0])) {
734 return Helper::NapiHelper::GetUndefinedValue(env);
735 }
736 std::string content = "Assertion failed";
737 if (argc > 1) {
738 content += ":";
739 content += MakeLogContent(env, info, argc, 1); // startIndex = 1
740 }
741 HILOG_ERROR("%{public}s%{public}s", groupIndent.c_str(), content.c_str());
742 return Helper::NapiHelper::GetUndefinedValue(env);
743 }
744
InitConsoleModule(napi_env env)745 void Console::InitConsoleModule(napi_env env)
746 {
747 napi_property_descriptor properties[] = {
748 DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("log", ConsoleLog<LogLevel::INFO>),
749 DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("debug", ConsoleLog<LogLevel::DEBUG>),
750 DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("info", ConsoleLog<LogLevel::INFO>),
751 DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("warn", ConsoleLog<LogLevel::WARN>),
752 DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("error", ConsoleLog<LogLevel::ERROR>),
753 DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("fatal", ConsoleLog<LogLevel::FATAL>),
754 DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("group", Group),
755 DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("groupCollapsed", Group),
756 DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("groupEnd", GroupEnd),
757 DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("table", Table),
758 DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("time", Time),
759 DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("timeLog", TimeLog),
760 DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("timeEnd", TimeEnd),
761 DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("trace", Trace),
762 DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("assert", Assert),
763 DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("count", Count),
764 DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("countReset", CountReset),
765 DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("dir", Dir),
766 DECLARE_NAPI_DEFAULT_PROPERTY_FUNCTION("dirxml", ConsoleLog<LogLevel::INFO>)
767 };
768 napi_value globalObj = Helper::NapiHelper::GetGlobalObject(env);
769 napi_value console = nullptr;
770 napi_create_object(env, &console);
771 napi_define_properties(env, console, sizeof(properties) / sizeof(properties[0]), properties);
772 napi_set_named_property(env, globalObj, "console", console);
773 }
774 } // namespace Commonlibrary::JsSysModule