uni app 的app端 写入运行日志到指定文件夹。

发布于:2025-09-04 ⋅ 阅读:(11) ⋅ 点赞:(0)

uni app 的app 端 写入指定目录文件夹。并自动生成当前日期的日志文件。删除十日前的日志文件

其中 writefile.js 代码如下

const {
	default: logger
} = require("./logger")

var name
var url
var params
var method
var res

function setlog(name, url, params, method) {
	this.name = name
	this.url = url
	this.params = params
	this.method = method

}

function setres(res) {
	this.res = res
}

function savelog() {
	var logs = {
		操作: this.name,
		接口: this.url,
		参数: this.params,
		接口方式: this.method,
		返回: this.res
	}
	logger.log(JSON.stringify(logs))
}

function removelog() {
	logger.removeFile(10)
}


module.exports = {
	setlog: setlog,
	savelog: savelog,
	setres: setres,
	removelog: removelog
};

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;
}
/**
 * @param {Object} tag 标识
 * @param {Object} msg 空格
 */
function writeToTxt(tag) {
	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 fileName = getLogFileName();
	// 获取当前时间
	let txt_msg = getTimeStr() + '\t[' + tag + ']\t' + msgs + '\n';
	if (tag == 'ERROR') {
		console.error(txt_msg);
	} else {
		// //console.log(txt_msg);
	}
	// #ifdef APP-PLUS
	plus.io.resolveLocalFileSystemURL(fileName, (fs) => {
		// //console.log(fs);
	});

	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;

代码中参考了其他大佬的部分代码。具体时谁的忘了。见谅

使用

import writeFile from '../../utils/writeFile'

    writeFile.setlog("登录按钮点击", url, params, "post")

    res 为接口返回值

    writeFile.setres(res)
    writeFile.savelog()


网站公告

今日签到

点亮在社区的每一天
去签到