0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Unity】ILogHandlerのドキュメントのサンプルをいじって動かしてみる

Posted at

はじめに

UnityのドキュメントのILogHandlerにサンプルコードが記載されてたので試してみる。

実装

実装にあたって以下の内容を対応する

  1. ログファイルの出力先をLogsフォルダに変更する
  2. ファイルストリームを閉じてないので閉じるようにする
  3. ILogHandlerが適応されているの分かりやすくするため、Debug.Logからログの出力をする
MyFileLogHandler.cs
using System;
using System.IO;
using UnityEngine;

public class MyFileLogHandler : ILogHandler, IDisposable
{
    private FileStream _fileStream;
    private StreamWriter _streamWriter;
    private readonly ILogHandler _defaultLogHandler;

    public MyFileLogHandler(ILogHandler defaultLogHandler)
    {
#if UNITY_EDITOR
        string filePath = Application.dataPath + "/../Logs/MyLogs.txt";
#else
        string filePath = Application.persistentDataPath + "/MyLogs.txt";
#endif
        _fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
        _streamWriter = new StreamWriter(_fileStream);
        _defaultLogHandler = defaultLogHandler;
    }

    public void Dispose()
    {
        if(_streamWriter != null)
        {
            _streamWriter.Close();
            _streamWriter = null;
        }
        if(_fileStream != null)
        {
            _fileStream.Close();
            _fileStream = null;
        }
    }

    public void LogFormat(LogType logType, UnityEngine.Object context, string format, params object[] args)
    {
        string formatEx = "[MyFileLogHandler]:" + format;
        if(_streamWriter != null)
        {
            //ログをファイルに書き込む
            _streamWriter.WriteLine(String.Format(formatEx, args));
            _streamWriter.Flush();
        }
        _defaultLogHandler.LogFormat(logType, context, formatEx, args);
    }

    public void LogException(Exception exception, UnityEngine.Object context)
    {
        _defaultLogHandler.LogException(exception, context);
    }
}


MyGameClass.cs
using UnityEngine;

public class MyGameClass : MonoBehaviour
{
    private MyFileLogHandler _fileLogHandler;
    void Start()
    {
        Debug.Log("MyGameClass Start before");
        _fileLogHandler = new MyFileLogHandler(Debug.unityLogger.logHandler);
        Debug.unityLogger.logHandler = _fileLogHandler;
        Debug.Log("MyGameClass Start after");
    }

    void OnDestroy()
    {
        _fileLogHandler.Dispose();
    }
}


実行結果

スクリーンショット

スクリーンショット

MyFileLogHandlerを設定した後に、MyFileLogHandlerの内容が反映され、Logsフォルダ内にLogファイルが生成されました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?