uniapp日志写入

1.来源于:

html5 plus 记录日志 - DCloud 插件市场

2.公共目录中建一个文件夹:walker-logger.js

/**
* 标题:自定义日志存储在txt中
* 说明:
1. 自定义日志存储在txt中
2. 生成的文件存放在对应app目录下的 _doc/logs 文件夹中
··· js
// main.js 文件进行全局挂载
// 引入logger
import logger from  '@/components/libs/logger.js'
// 挂载logger
uni.$console = logger;
```
...
* 使用方法 *********************************************
* 1. 使用全局挂载的方式(和console)一致
* uni.$console.debug('日志信息');
* uni.$console.log('日志信息');
* uni.$console.info('日志信息');
* uni.$console.warn('日志信息');
* uni.$console.error('日志信息');

* 2. 在普通js文件单独引入的方法
* import logger from '@/path/to/the/logger.js'
* logger.log('日志信息')
* logger.error('日志信息')

 */

// 日志存放的文件夹目录
const LOG_DIR = "_doc/logs";
/**
 * 获取当前时间
 */
function getDayStr() {
  var y, m, d, h, mm, s;
  var date = new Date();
  y = date.getFullYear();
  m = date.getMonth() + 1;
  d = date.getDate();
  m = m < 10 ? "0" + m : m;
  d = d < 10 ? "0" + d : d;
  // //console.log('日期:',y,m,d)
  // return '20220607' // 生成指定日期
  return "" + y + m + d;
}
/**
 * 获取当前时间,yyyy-mm-dd hh:mm:ss
 * 用于记录日志的时间信息
 */
function getTimeStr() {
  var y, m, d, h, mm, s;
  var date = new Date();
  y = date.getFullYear();
  m = date.getMonth() + 1;
  d = date.getDate();
  h = date.getHours();
  mm = date.getMinutes();
  s = date.getSeconds();
  m = m < 10 ? "0" + m : m;
  d = d < 10 ? "0" + d : d;
  h = h < 10 ? "0" + h : h;
  mm = mm < 10 ? "0" + mm : mm;
  s = s < 10 ? "0" + s : s;
  var timeStr = y + "-" + m + "-" + d + " " + h + ":" + mm + ":" + s;
  return timeStr;
}
/**
 * 日志TXT的名称
 */
function getLogFileName() {
  const txt = LOG_DIR + "/" + getDayStr() + ".txt";
  console.log("TXT文件名称:", txt);
  return txt;
}
let tasks = [];
/**
 * @param {Object} tag 标识
 * @param {Object} msg 空格
 */
function writeToTxt(tag) {
  return new Promise((resolve, reject) => {
    let msgs = "";
    for (var i = 1; i < arguments.length; i++) {
      const item = arguments[i];
      if (
        typeof item == "string" ||
        typeof item == "number" ||
        typeof item == "boolean"
      ) {
        msgs = msgs + "\t" + item;
      } else {
        msgs = msgs + "\t" + JSON.stringify(item);
      }
    }
    // 获取当前时间
    let txt_msg = getTimeStr() + "\t[" + tag + "]\t" + msgs + "\n";
    if (tag == "ERROR") {
      console.error(txt_msg);
    } else {
      // //console.log(txt_msg);
    }
    tasks.push(txt_msg);
    resolve(true);
  }).then(() => {
    clearTask();
  });
}
// 清空日志到日志文件
function clearTask() {
  // #ifdef APP-PLUS
  if (tasks.length === 0) {
    return;
  }
  const txt_msg = tasks.join("");
  tasks = [];
  const fileName = getLogFileName();
  plus.io.requestFileSystem(
    plus.io.PRIVATE_DOC,
    (fs) => {
      fs.root.getFile(
        fileName,
        {
          create: true,
        },
        function (entry) {
          // 写入到本地
          entry.createWriter(
            function (writer) {
              writer.onwrite = function (e) {
                // console.log("Write data success!");
                console.log("写入本地日志 >>>> ", txt_msg);
              };
              writer.onerror = function (e) {
                console.eror(
                  "写入本地日志失败 >>>> ",
                  JSON.stringify(e),
                  txt_msg
                );
              };
              // Write data to the end of file.
              writer.seek(writer.length);
              writer.write(txt_msg);
            },
            function (e) {
              console.log(e.message);
            }
          );
        }
      );
    },
    function (e) {
      console.log("Request file system failed: " + JSON.stringify(e));
    }
  );
  // #endif
}

/**
 * 压缩所有的日志为zip
 */
function zipLogDir(callback) {
  //console.log('开始压缩');
  // #ifdef APP-PLUS
  var zipFile = "_doc/logs.zip";
  var targetPath = LOG_DIR;

  // 开始压缩文件
  console.log("开始压缩", targetPath, zipFile);
  plus.zip.compress(
    targetPath,
    zipFile,
    function (res) {
      console.log("开始压缩 Compress success!", res);
      if (callback) {
        callback({
          success: true,
          res,
          zipPath: zipFile,
        });
      }
    },
    function (error) {
      console.error("开始压缩 Compress error!", error);
      if (callback) {
        callback({
          success: false,
          error,
        });
      }
    }
  );
  // #endif
}
/**
 * 删除多少天之前的日志文件
 */
function removeFile(durationDay) {
  return new Promise((resolve, reject) => {
    if (!durationDay || durationDay <= 0) {
      durationDay = 10;
    }
    var dirPath = LOG_DIR;
    plus.io.resolveLocalFileSystemURL(
      dirPath,
      function (entry) {
        //读取这个目录对象
        var directoryReader = entry.createReader();
        // console.log(dirPath)
        //读取这个目录下的所有文件
        directoryReader.readEntries(
          function (entries) {
            console.log("日志文件数量", entries.length);
            //如果有才操作
            if (entries.length > 0) {
              let now = getDayStr();
              for (let file of entries) {
                // console.log(file.name);
                // 判断需要保留的日志
                let day = file.name.replace(".txt", "");
                // console.log(parseInt(day) + parseInt(durationDay) < parseInt(now));
                // console.log(parseInt(day));
                // console.log(parseInt(durationDay));
                // console.log(parseInt(day) + parseInt(durationDay));
                // console.log(parseInt(now));
                if (parseInt(day) + parseInt(durationDay) < parseInt(now)) {
                  console.log("需要删除的日志是", file.name);
                  try {
                    file.remove(
                      function () {
                        console.error("删除日志成功", file.name);
                      },
                      function (e) {
                        console.error("删除日志失败", file.name, e);
                      }
                    );
                  } catch (e) {
                    console.error("删除日志失败", file.name, e);
                  }
                } else {
                  console.log("保留的日志是", file.name);
                }
              } // for
            } // if
            resolve();
          },
          function (e) {
            console.log("读取文件失败:" + e.message);
            resolve();
          }
        );
      },
      function (e) {
        console.log("读取目录失败:" + e.message);
        resolve();
      }
    );
  });
}

/**
 * 自定义TXT日志
 */
const logger = {
  /**
   * @param {Object} msg 日志信息的字符串信息
   */
  debug: function () {
    writeToTxt("DEBUG", ...arguments);
    console.debug(...arguments);
  },
  log: function () {
    writeToTxt("LOG", ...arguments);
    console.log(...arguments);
  },
  info: function () {
    writeToTxt("INFO", ...arguments);
    console.info(...arguments);
  },
  warn: function () {
    writeToTxt("WARN", ...arguments);
    console.warn(...arguments);
  },
  error: function () {
    writeToTxt("ERROR", ...arguments);
    console.error(...arguments);
  },
  /**
   * @param {String} tag 日志信息的自定义信息
   */
  tag: function (tag) {
    writeToTxt(tag, ...arguments);
    console.log(...arguments);
  },
  /**
   * @param {Object} msg 日志信息的字符串信息
   */
  network: function () {
    writeToTxt("NETWORK", ...arguments);
    console.log(...arguments);
  },
  /**
   * @param {Object} msg 日志信息的字符串信息
   */
  logIpExchange: function (msg) {
    writeToTxt("IpExchange", ...arguments);
    console.log(...arguments);
  },
  /**
   * 压缩成zip,并返回路径
   * @param {Object} callback
   */
  zipLogDir,
  /**
   * 删除多少${durationDay}天之前的日志文件
   * @param {Object} durationDay 默认是10天
   */
  removeFile,
  /**
   * 主要使用方法。先移除
   * @param {Object} callback
   */
  removeFileAndZipLogDir(callback) {
    removeFile().then(() => {
      zipLogDir(callback);
    });
  },
};

export default logger;

3.全局定义

 //日志文件挂载

import logger from "./util/walker-logger";

uni.$console = logger;

4.组件中引用

 uni.$console.error('11');

相关推荐

  1. uniapp日志写入

    2024-01-30 08:22:02       38 阅读
  2. 如何在Node.js将console日志写入到文件

    2024-01-30 08:22:02       36 阅读
  3. thinphp 调用 \think\Log::write 写入回调日志信息

    2024-01-30 08:22:02       39 阅读
  4. Spring Boot + Logback 实现日志记录写入文件

    2024-01-30 08:22:02       10 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-30 08:22:02       19 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-30 08:22:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-30 08:22:02       20 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-30 08:22:02       20 阅读

热门阅读

  1. WebSocket详解

    2024-01-30 08:22:02       29 阅读
  2. 实时搜索建议

    2024-01-30 08:22:02       35 阅读
  3. log4j 日志级别及优先级排序

    2024-01-30 08:22:02       45 阅读
  4. Ruby安装演示教程

    2024-01-30 08:22:02       33 阅读