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;
        }
    }
}
相关推荐
SRC_BLUE_1721 小时前
NSSCTF - Web | 【第五空间 2021】pklovecloud
android·前端
小剑修21 小时前
2025.10.18 复习
unity
tq10861 天前
学习Hilt注解
android
2501_915921431 天前
iOS 应用代上架流程,多工具组合与使用 开心上架 跨平台自动化上传指南
android·ios·小程序·uni-app·自动化·cocoa·iphone
日日行不惧千万里1 天前
2025最新仿默往 IM 即时通讯系统源码(PC + Web + iOS + Android)完整版发布!
android·ios
歪歪1001 天前
React Native开发Android&IOS流程完整指南
android·开发语言·前端·react native·ios·前端框架
雪芽蓝域zzs1 天前
uniapp 修改android包名
android·uni-app
AA陈超1 天前
虚幻引擎5 GAS开发俯视角RPG游戏 P05-11 消息小部件
c++·游戏·ue5·游戏引擎·虚幻
用户2018792831671 天前
厨房里的协程大冒险:launch与async的烹饪之旅
android
用户2018792831671 天前
浅析协程与挂起函数实现原理
android