Unity的日志管理类

脚本功能:

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;
        }
    }
}
相关推荐
成都大菠萝2 分钟前
2-2-8 快速掌握Kotlin-vararg关键字与get函数
android
成都大菠萝2 分钟前
2-2-7 快速掌握Kotlin-泛型类型约束
android
城东米粉儿8 分钟前
Collections.synchronizedMap()与ConcurrentHashMap的区别笔记
android
愤怒的代码13 分钟前
深入解析 Binder 运行的状态
android·app
nnsix14 分钟前
Unity 反编译dll(Windows平台)
unity
XR技术研习社1 小时前
四种安装特定版本Package的方法
unity·ar·xr·vr
2501_915106321 小时前
iOS App 测试方法,通过 Xcode、Instruments、Safari Inspector、克魔(KeyMob)等工具
android·ios·小程序·uni-app·iphone·xcode·safari
游戏开发爱好者81 小时前
对 iOS IPA 文件进行深度混淆的一种实现路径
android·ios·小程序·https·uni-app·iphone·webview
成都大菠萝2 小时前
2-2-5 快速掌握Kotlin-语言的泛型函数
android
成都大菠萝2 小时前
2-2-4 快速掌握Kotlin-定义泛型类
android