1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Unity】ラベルつきログ出力をラクに実装にする

Posted at

ラベル付きでログ出力するやつ

image.png

こういうやつです。[かっこ]で囲ってログの出どころが一目でわかるようにします。
ついでにConsoleウィンドウでフィルタリングできて非常に便利です。

この実装、Debug.Log("[Hoge] " + fuga)みたいなコードを書くのがシンプルですが、毎度これをやるのもかったるいものです。

楽にする

こういうインターフェースを作成します。

public interface ILoggerSubject
{
    string LoggerName { get; }
}

次に、このILoggerSubjectに対して拡張メソッドを定義します。

using UnityEngine;
using Object = UnityEngine.Object;

public static class LoggerSubjectExtension
{
    public static void Log(this ILoggerSubject sender, string message, Object context = null) =>
        Debug.Log($"[{sender.LoggerName}] {message}", context);
}

こうすると、ILoggerSubjectを実装したクラスの中で this.Log()と書くだけでラベル付きでログが出力されます。

Hoge.cs
public class Hoge : MonoBehaviour, ILoggerSubject
{
    void Start()
    {
        this.Log("Fuga");
    }

    public string LoggerName => "Hoge";
}

LoggerNameいっこ実装するだけでDebug.Logと遜色ない書き心地でログ出力できるのがイチオシポイントです。

最後にWarningとErrorにも対応します。ついでに、structから呼んだ時のboxing回避のためにジェネリクス対応をしておきます。

using System;
using UnityEngine;
using Object = UnityEngine.Object;

public static class LoggerSubjectExtension
{
    public static void Log<T>(this T sender, string message, Object context = null) where T : ILoggerSubject
    {
        Debug.Log($"[{sender.LoggerName}] {message}", context);
    }
    
    public static void LogWarning<T>(this T sender, string message, Object context = null) where T : ILoggerSubject
    {
        Debug.LogWarning($"[{sender.LoggerName}] {message}", context);
    }
    
    public static void LogError<T>(this T sender, string message, Object context = null) where T : ILoggerSubject
    {
        Debug.LogError($"[{sender.LoggerName}] {message}", context);
    }

    public static void LogException<T>(this T sender, Exception exception, Object context = null) where T : ILoggerSubject
    {
        Debug.LogException(exception, context);
    }
}
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?