log.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /*
  2. * @Author: fuyu
  3. * @Date: 2021-03-23 16:25:59
  4. * @LastEditors: fuyu
  5. * @LastEditTime: 2021-03-25 17:28:20
  6. * @FilePath: /202103/code/sql_merge/src/service/log.js
  7. */
  8. const fs = require('fs')
  9. const path = require('path');
  10. const rootPath = path.join(__dirname, '..', '..', 'logs')
  11. import {getNowDay, getNowTime} from './time'
  12. export async function logSum(institution_id, count) {
  13. const dirPath = path.join(rootPath, 'sum')
  14. checkPath(dirPath)
  15. const filePath = path.join(dirPath, getNowDay() + '.log')
  16. const time = getNowTime()
  17. const obj = {
  18. time: time, institution_id, count,
  19. }
  20. fs.appendFileSync(filePath, JSON.stringify(obj) + '\r\n')
  21. fs.writeFileSync(path.join(dirPath, institution_id + '-' + getNowDay() + '.log'), count + '')
  22. }
  23. export async function logSingle(name) {
  24. checkPath(rootPath)
  25. const filePath = path.join(rootPath, name + '.log')
  26. let count = 0
  27. if(fs.existsSync(filePath)) {
  28. let str = fs.readFileSync(filePath)
  29. if(str) {
  30. try {
  31. let obj = JSON.parse(fs.readFileSync(filePath)) || {}
  32. count = obj['count'] || 0
  33. } catch (error) {
  34. console.log('err: JSON.parse logSingle', error)
  35. }
  36. }
  37. }
  38. count = parseInt(count) + 1
  39. const time = getNowTime()
  40. fs.writeFileSync(filePath, JSON.stringify({time, count}))
  41. }
  42. const checkPath = filePath => {
  43. if(fs.existsSync(filePath)) {
  44. return true
  45. }
  46. return fs.mkdirSync(filePath, { recursive: true })
  47. }