1/*
2 * Copyright (c) 2022-2023 Shenzhen Kaihong Digital Industry Development 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
16class NapiLog {
17  constructor() {}
18}
19NapiLog.LEV_NONE = 0;
20NapiLog.LEV_ERROR = 1;
21NapiLog.LEV_DEBUG = 2;
22NapiLog.LEV_INFO = 3;
23
24const LEV_STR = ['[NON]', '[ERR]', '[DBG]', '[INF]'];
25var logLevel = NapiLog.LEV_ERROR;
26var logFileName = null;
27var logResultMessage = [true, ''];
28var errorCallBack = null;
29
30function getDateString() {
31  let nowDate = new Date();
32  return nowDate.toLocaleString();
33}
34
35function saveLog(dateStr, levStr, detail) {
36  if (logFileName) {
37    let logStr = dateStr + ' ' + levStr + ' ' + detail + '\n';
38  }
39}
40
41NapiLog.init = function (level, fileName) {
42  logLevel =
43    level in
44    [NapiLog.LEV_NONE, NapiLog.LEV_ERROR, NapiLog.LEV_DEBUG, NapiLog.LEV_INFO] ? level : NapiLog.LEV_ERROR;
45  logFileName = fileName ? fileName : 'napi_generator.log';
46};
47
48function recordLog(lev, ...args) {
49  let dataStr = getDateString();
50  let detail = args.join(' ');
51  saveLog(dataStr, LEV_STR[lev], detail);
52  if (lev == NapiLog.LEV_ERROR) {
53    logResultMessage = [false, detail];
54    if (errorCallBack != null) {
55      errorCallBack(detail);
56    }
57  }
58  if (logLevel < lev) {
59    return;
60  }
61  console.log(dataStr, LEV_STR[lev], detail);
62}
63
64NapiLog.logError = function (...args) {
65  recordLog(NapiLog.LEV_ERROR, args);
66};
67
68NapiLog.logDebug = function (...args) {
69  recordLog(NapiLog.LEV_DEBUG, args);
70};
71
72NapiLog.logInfo = function (...args) {
73  recordLog(NapiLog.LEV_INFO, args);
74};
75
76NapiLog.getResult = function () {
77  return logResultMessage;
78};
79
80NapiLog.clearError = function () {
81  logResultMessage = [true, ''];
82};
83
84NapiLog.registError = function (func) {
85  errorCallBack = func;
86};
87
88module.exports = {
89  NapiLog,
90};
91