Unity 사용자 정의 로그 저장 에 대한 질문

머리말    
   이전에 유 니 티 5.x 는 코드 에 debug.log..등 을 썼 습 니 다.포장 한 후에 현재 프로그램 폴 더 에 해당 하 는"outlog.txt"가 있 습 니 다.2017 년 이후 이 파일 은 CD 사용자 Appdata/LocalLow/회사 이름 으로 이동 되 었 습 니 다. 폴 더 아래.불편 해서 혼자 썼어 요.
코드

using UnityEngine;
using System.IO;
using System;
using System.Diagnostics;
using Debug = UnityEngine.Debug;
 
public class DebugTrace
{
    private FileStream fileStream;
    private StreamWriter streamWriter;
 
    private bool isEditorCreate = false;//              
    private int showFrames = 1000;  //    
 
    #region instance
    private static readonly object obj = new object();
    private static DebugTrace m_instance;
    public static DebugTrace Instance
    {
        get
        {
            if (m_instance == null)
            {
                lock (obj)
                {
                    if (m_instance == null)
                        m_instance = new DebugTrace();
                }
            }
            return m_instance;
        }
    }
    #endregion
 
    private DebugTrace()
    {
 
    }
  
    /// <summary>
    ///         
    /// </summary>
    public void StartTrace()
    {
        if (Debug.unityLogger.logEnabled)
        {
            if (Application.isEditor)
            {
                //       isEditorCreate==true      
                if (isEditorCreate)
                {
                    CreateOutlog();
                }
            }
            //                Debug.unityLogger.logEnabled   
            else
            {
                CreateOutlog();
            }
        }
    }
    private void Application_logMessageReceivedThreaded(string logString, string stackTrace, LogType type)
    {
        //  Debug.Log(stackTrace);  //   staackTrace          
        if (type != LogType.Warning)
        {
            // StackTrace stack = new StackTrace(1,true); //    ?(1) 
            StackTrace stack = new StackTrace(true);  //     
            string stackStr = string.Empty;
 
            int frameCount = stack.FrameCount;  //  
            if (this.showFrames > frameCount) this.showFrames = frameCount;  //              
 
            //       ,          
            for (int i = stack.FrameCount - this.showFrames; i < stack.FrameCount; i++)
            {
                StackFrame sf = stack.GetFrame(i);  //       
                                                    // 1:       ps:GetFileLineNumber           
                stackStr += "at [" + sf.GetMethod().DeclaringType.FullName +
                            "." + sf.GetMethod().Name +
                            ".Line:" + sf.GetFileLineNumber() + "]
"; // tostring // stackStr += sf.ToString(); } // stackStr = stack.ToString(); string content = string.Format("time: {0} logType: {1} logString: {2}
stackTrace: {3} {4} ", DateTime.Now.ToString("HH:mm:ss"), type, logString, stackStr, "\r
"); streamWriter.WriteLine(content); streamWriter.Flush(); } } private void CreateOutlog() { if (!Directory.Exists(Application.dataPath + "/../" + "OutLog")) Directory.CreateDirectory(Application.dataPath + "/../" + "OutLog"); string path = Application.dataPath + "/../OutLog" + "/" + DateTime.Now.ToString("yyyyMMddHHmmss") + "_log.txt"; fileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite); streamWriter = new StreamWriter(fileStream); Application.logMessageReceivedThreaded += Application_logMessageReceivedThreaded; } /// <summary> /// /// </summary> public void CloseTrace() { Application.logMessageReceivedThreaded -= Application_logMessageReceivedThreaded; streamWriter.Dispose(); streamWriter.Close(); fileStream.Dispose(); fileStream.Close(); } /// <summary> /// /// </summary> /// <param name="logEnable"> </param> /// <param name="showFrams"> 0 </param> /// <param name="filterLogType"> log </param> /// <param name="editorCreate"> </param> public void SetLogOptions(bool logEnable, int showFrams = 1, LogType filterLogType = LogType.Log, bool editorCreate = false) { Debug.unityLogger.logEnabled = logEnable; Debug.unityLogger.filterLogType = filterLogType; isEditorCreate = editorCreate; this.showFrames = showFrams == 0 ? 1000 : showFrams; } }
...에 대하 여 filterLogType
filter LogType 기본 설정 은 Log 입 니 다.모든 종류의 Log 를 표시 합 니 다.
경고:경고,Assert,Error,Exception 이 표 시 됩 니 다.
Assert:Assert,Error,Exception 이 표 시 됩 니 다.
Error:Error 와 Exception 표시
Exception:Exception 만 표 시 됩 니 다.
쓰다

using UnityEngine;
 
public class Test : MonoBehaviour
{
    private BoxCollider boxCollider;
    void Start()
    {
        DebugTrace.Instance.SetLogOptions(true, 2, editorCreate: true); //         2            
        DebugTrace.Instance.StartTrace();
        Debug.Log("log");
        Debug.Log("log", this);
        Debug.LogError("LogError");
        Debug.LogAssertion("LogAssertion");
      
        boxCollider.enabled = false;  //           
    }
 
    private void OnApplicationQuit()
    {
        DebugTrace.Instance.CloseTrace();
    }
}
편집기 에 도 로그 생 성 을 설정 하면 로그 파일 은 현재 항목 경로 에서 압축 된 후 exe 동급 디 렉 터 리 에서
패키지 발표 후 일부 데 이 터 는 줄 번호 와 같은 데 이 터 를 가 져 올 수 없습니다.
StackFrame 참조

마지막 으로 효과 보기:

모자라다
발표 버 전에 이상 이 생 겨 줄 번호 가 잡 히 지 않 습 니 다.
debug 버 전 은 DevelopMend build 를 선택 하여 더 많은 정 보 를 포착 할 수 있 습 니 다.

유 니 티 사용자 정의 로그 저장 에 관 한 이 야 기 를 나 누 는 글 은 여기까지 입 니 다.더 많은 유 니 티 로그 저장 내용 은 이전 글 을 검색 하거나 아래 글 을 계속 찾 아 보 세 요.앞으로 도 많은 응원 부 탁 드 리 겠 습 니 다!

좋은 웹페이지 즐겨찾기