This package allows using of the .NET logging API in Unity.
Add the package (instructions) using this Git URL:
https://github.com/Mini-IT/unity-logger.git
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)
- Create a logger factory
ILoggerFactory factory = new MiniIT.Logging.Unity.UnityLoggerFactory();
- Create a logger
ILogger logger = factory.CreateLogger("MyCategory");
- Write a log message with a specified log level
logger.LogTrace("Example trace"); logger.LogWarning("Example warning"); logger.LogError("Example error");
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");
}
}
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);
});
});