55 lines
1.9 KiB
Plaintext
55 lines
1.9 KiB
Plaintext
import { WriteApi } from '../interface';
|
|
import SimpleDateFormat from 'java.text.SimpleDateFormat';
|
|
import Locale from 'java.util.Locale';
|
|
import FileOutputStream from 'java.io.FileOutputStream';
|
|
import File from 'java.io.File';
|
|
import Date from "java.util.Date";
|
|
import OutputStreamWriter from 'java.io.OutputStreamWriter';
|
|
import Log from 'android.util.Log';
|
|
const LOG_DISPLAY_NAME = "app_log.txt";
|
|
|
|
// 字符串转Uint8Array
|
|
function stringToUint8Array(str: string) : ByteArray{
|
|
const arr: ByteArray = new ByteArray(str.length);
|
|
for (let i = 0; i < str.length; i++) {
|
|
arr.set(i.toInt(), str.charCodeAt(i)!!.toByte());
|
|
}
|
|
return arr
|
|
}
|
|
|
|
// 创建消息格式
|
|
function createMessage(logMessage : string) : string {
|
|
const timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault()).format(new Date());
|
|
const logEntry = timestamp + " - " + logMessage + "\n";
|
|
Log.d("systech",logMessage);
|
|
return logEntry
|
|
}
|
|
|
|
// 写入日志
|
|
export const write : WriteApi = (logMessage : string) => {
|
|
const context = UTSAndroid.getAppContext();
|
|
// 获取应用的私有外部存储目录
|
|
const externalFilesDir = context!!.getExternalFilesDir(null); // type为null表示根目录
|
|
if (externalFilesDir == null) {
|
|
// 外部存储不可用或未挂载
|
|
return;
|
|
}
|
|
|
|
// 指定放在 应用的私有外部存储目录/Logs 目录中
|
|
const logDir = new File(externalFilesDir, `Logs`);
|
|
if (!logDir.exists()) {
|
|
logDir.mkdirs();
|
|
}
|
|
|
|
const nowDay = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
|
|
const fileName = `${nowDay}_${LOG_DISPLAY_NAME}`;
|
|
const logFile = new File(logDir, fileName);
|
|
try {
|
|
const fos = new FileOutputStream(logFile, true)
|
|
const oStreamWriter = OutputStreamWriter(fos, 'UTF-8')
|
|
oStreamWriter.append(createMessage(logMessage));
|
|
oStreamWriter.close()
|
|
} catch (e) {
|
|
console.log(e);
|
|
}
|
|
} |