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;
        }
    }
}
相关推荐
hunterandroid6 分钟前
[Android 从零到一] ARouter 路由框架原理:APT 生成路由表与组件化通信
android
最好一梦30 分钟前
佳维视安卓工控机在堆垛机中的应用
android
淡海水1 小时前
08-02-优化-LINQ与函数式编程的GC代价
unity·c#·.netcore·linq·gc
传奇开心果编程1 小时前
组合优先开发范式:从汉字造字原理到声明式UI组件组合思想
android·flutter·ios·swiftui·移动开发·harmonyos·android jetpack
腾讯端服务2 小时前
一码Duo端-Kuikly-iOS折叠屏新UI适配实践
android·ui·ios·kotlin·鸿蒙
T量子永生2 小时前
Android SISO 分布式编译集群配置方案
android·分布式·云计算·源代码管理
街头便衣2 小时前
OpenRouter周榜复算:164万亿token,输出2.55%,DeepSeek账单占1.4%
android·java·开发语言·人工智能·语言模型·开源
警醒与鞭策14 小时前
Codex桌面版与Claude桌面版使用设置
android·unity·ai·性能优化
xcLeigh16 小时前
Unity基础:Destroy与DestroyImmediate——正确销毁游戏物体的方式
游戏·unity·游戏引擎·教程
传奇开心果17 小时前
【Compose Multiplatform跨端声明式UI实用技术】第19课:多平台部署与发布
android·kotlin