Skip to content

.NET logging API wrapper for Unity

License

MIT, Unknown licenses found

Licenses found

MIT
LICENSE
Unknown
LICENSE.meta
Notifications You must be signed in to change notification settings

Mini-IT/unity-logger

Repository files navigation

unity-logger

This package allows using of the .NET logging API in Unity.

Installation

Add the package (instructions) using this Git URL:

https://github.com/Mini-IT/unity-logger.git

Install managed DLLs from NuGet

The dependency managed DLL are not included to avoid possible duplication. You need to add them to the project manually. You can extract the needed dlls from NuGet packages (either manually or using a tool like NuGetForUnity)

Usage

  1. Create a logger factory
    ILoggerFactory factory = new MiniIT.Logging.Unity.UnityLoggerFactory();
  2. Create a logger
    ILogger logger = factory.CreateLogger("MyCategory");
  3. Write a log message with a specified log level
    logger.LogTrace("Example trace");
    logger.LogWarning("Example warning");
    logger.LogError("Example error");

Example

using Microsoft.Extensions.Logging;
using MiniIT.Logging.Unity;
using ILogger = Microsoft.Extensions.Logging.ILogger;

public static class LogManager
{
  private static ILoggerFactory s_factory;
  public static ILoggerFactory Factory => s_factory ??= new MiniIT.Logging.Unity.UnityLoggerFactory();

  private static ILogger s_defaultLogger;
  public static ILogger DefaultLogger => s_defaultLogger ??= Factory.CreateLogger("");
}

public class LoggerExample : MonoBehaviour
{
  private ILogger _logger;

  void Start()
  {
    _logger = LogManager.Factory.CreateLogger<LoggerExample>();         // category is the full class name
    //_logger = LogManager.Factory.CreateLogger(nameof(LoggerExample)); // category is the short class name
    //_logger = LogManager.Factory.CreateLogger("LoggerExample");       // custom category

    _logger.LogTrace("Start");
  }

  void Update()
  {
    if (Input.GetKeyDown(KeyCode.Space))
    {
      _logger.LogTrace("Space pressed at {0}", Time.realtimeSinceStartup);
    }
  }
}

public class DefaultLoggerExample : MonoBehaviour
{
  void Start()
  {
    LogManager.DefaultLogger.LogTrace("Default logger message");
  }
}

ZLogger

Since this logger and ZLogger both use the same API they can be interchanged by simply changing the factory.

using Microsoft.Extensions.Logging;
using ZLogger;
using Cysharp.Text;

factory = ZLogger.UnityLoggerFactory.Create(builder =>
{
  builder.SetMinimumLevel(LogLevel.Trace);
  builder.AddZLoggerUnityDebug(options =>
  {
    options.PrefixFormatter = (writer, info) => ZString.Utf8Format(writer, "[{0}] ", info.CategoryName);
  });
});

About

.NET logging API wrapper for Unity

Resources

License

MIT, Unknown licenses found

Licenses found

MIT
LICENSE
Unknown
LICENSE.meta

Stars

Watchers

Forks

Packages

No packages published

Languages