脚本功能:
1,打印日志到控制台
2,显示日志到UI Text
3,将日志写入本地文件
这对unity开发安卓平台来说很有用
csharp
using System;
using System.IO;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
public class FileLogger : MonoBehaviour
{
public static FileLogger Instance;
public Text LogText;
private string logFilePath;
private StringBuilder _logBuilder = new StringBuilder();
private int _lineCount = 0;
private const int MaxLines = 25;
void Awake()
{
if (Instance == null)
{
Instance = this;
}
}
void Start()
{
// 注册日志回调
Application.logMessageReceived += HandleLog;
// 确定日志文件路径
logFilePath = "sdcard/game_log.txt";
// 检查是否需要删除旧日志(第二天才删除)
CheckAndDeleteOldLog();
}
void OnDestroy()
{
// 取消注册
Application.logMessageReceived -= HandleLog;
}
void CheckAndDeleteOldLog()
{
if (File.Exists(logFilePath))
{
DateTime lastWriteTime = File.GetLastWriteTime(logFilePath);
DateTime today = DateTime.Now.Date;
// 如果日志文件不是今天创建的,则删除
if (lastWriteTime.Date < today)
{
File.Delete(logFilePath);
Debug.Log($"删除旧的日志文件:{lastWriteTime.ToShortDateString()}");
}
}
File.AppendAllText(logFilePath, "日志记录器初始化\n");
}
void HandleLog(string logString, string stackTrace, LogType type)
{
// 构造日志条目
string logEntry = $"[{DateTime.Now}] [{type}] {logString}\n";
if (type == LogType.Error || type == LogType.Exception)
{
logEntry += $"{stackTrace}\n";
}
// 写入文件
try
{
File.AppendAllText(logFilePath, logEntry);
}
catch (Exception e)
{
Debug.LogError($"无法将日志写入文件: {e.Message}");
}
}
public void MyLog(object str, int level = 0)
{
if (LogText == null)
return;
// 添加新行
_logBuilder.Insert(0, $"{str}\n");
_lineCount++;
// 如果超过最大行数,移除最旧的行
if (_lineCount > MaxLines)
{
int lastNewLineIndex = _logBuilder.ToString().LastIndexOf('\n', _logBuilder.Length - 1);
if (lastNewLineIndex != -1)
{
_logBuilder.Length = lastNewLineIndex;
_lineCount--;
}
}
LogText.text = _logBuilder.ToString();
// 输出到 Unity 控制台
switch (level)
{
case 0: Debug.Log(str); break;
case 1: Debug.LogError(str); break;
}
}
}