vue2 txt日志打印以及读取txt文本数据

1.创建log.js在根目录下

let fs = require('fs')
import { parseTime } from "./src/renderer/utils/index"
import { MessageBox } from 'element-ui'
function writeLog(value){  
  let logAddress =localStorage.getItem('logAddress')
  logAddress = logAddress?.replace(/\\/g, '/')
  if(logAddress?.charAt(logAddress.length - 1) !== '\/'){
    logAddress += '\/'
  } 
  fs.mkdirSync(logAddress, { recursive: true })  
  let date = parseTime(new Date(),'{y}-{m}-{d}')+'的日志'
  let filePath = `${logAddress}${date}.txt` 
  let time = parseTime(new Date(),'{h}:{i}:{s}.{t}')
  try{ 
    fs.appendFileSync(filePath, `${time}:${value}\n`, err => {
      if (err) { 
        console.info(err)
        throw err
      }
    })
  }catch (error) {
    MessageBox.alert('日志写入出错,请联系管理员解决', '日志写入异常')
    console.error('An error occurred while appending data:', error)
  }
}   
export default writeLog

2.  index.js 时间格式的封装

 export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
    t:date.getMilliseconds()
  }
  const time_str = format.replace(/{([ymdhisat])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    if (key === 't') { return value.toString().padStart(3, '0') }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

3.使用

getLogAddress(){  
      let _this = this
      let settingFilePath = process.env.NODE_ENV == 'production'? process.resourcesPath + '/setting/log.txt' : path.resolve(__dirname, "../../setting/log.txt")
      const r1 = readline.createInterface({
        input: fs.createReadStream(settingFilePath)
      }) 
      let arr = []
      var i = 1 //txt中的行数
      r1.on('line', function(line){ 
        arr.push(line)  
        i+=1
      })   
      r1.on('close', () => {    
        if(arr.length && arr[1]){
            localStorage.setItem('logAddress',arr[1]) 
        }else{
          let address = process.env.NODE_ENV == 'production'? process.resourcesPath + "/logs/" : path.resolve(__dirname, "../../logs/")
          localStorage.setItem('logAddress',address)  
        }  
      })   
    },



import writeLog from '../../log'

writeLog('---软件启动---') 

4.记得在package.json 添加log的配置,在安装文件里面会看到日志

"build": { 
    "extraResources": [ 
      {
        "from": "setting/",
        "to": "setting/"
      },
      {
        "from": "logs/",
        "to": "logs/"
      }
    ],
  },

  

posted @ 2024-03-21 11:45  福超  阅读(202)  评论(0编辑  收藏  举报