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;
        }
    }
}
相关推荐
androidwork1 小时前
深入解析内存抖动:定位与修复实战(Kotlin版)
android·kotlin
梦天20152 小时前
android核心技术摘要
android
KhalilRuan3 小时前
Unity-MMORPG内容笔记-其一
unity·游戏引擎
szhangbiao3 小时前
“开发板”类APP如果做屏幕适配
android
高林雨露4 小时前
RecyclerView中跳转到最后一条item并确保它在可视区域内显示
android
移动开发者1号7 小时前
ReLinker优化So库加载指南
android·kotlin
山野万里__7 小时前
C++与Java内存共享技术:跨平台与跨语言实现指南
android·java·c++·笔记
Huckings7 小时前
Android 性能问题
android
移动开发者1号7 小时前
剖析 Systrace:定位 UI 线程阻塞的终极指南
android·kotlin
移动开发者1号7 小时前
深入解析内存抖动:定位与修复实战(Kotlin版)
android·kotlin