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;
        }
    }
}
相关推荐
my_power5201 天前
车载安卓面试题汇总
android
csj501 天前
安卓基础之《(15)—内容提供者(1)在应用之间共享数据》
android
yeziyfx1 天前
kotlin中 ?:的用法
android·开发语言·kotlin
2501_915918411 天前
只有 Flutter IPA 文件,通过多工具组合完成有效混淆与保护
android·flutter·ios·小程序·uni-app·iphone·webview
robotx1 天前
AOSP 设置-提示音和振动 添加一个带有开关(Switch)的设置项
android
青莲8431 天前
RecyclerView 完全指南
android·前端·面试
青莲8431 天前
Android WebView 混合开发完整指南
android·前端·面试
龙之叶1 天前
【Android Monkey源码解析三】- 运行解析
android
KevinWang_1 天前
Android 的 assets 资源和 raw 资源有什么区别?
android
码农幻想梦1 天前
2021Android从零入门到实战(慕课网官方账号)
android