Skip to content

Logging

Cedric Decoster edited this page Jan 15, 2024 · 3 revisions

Overview

This guide explains how to integrate and use Serilog logging in Unity projects. The underlying Substrate .NET API uses Serilog as a powerful logging library that provides enhanced logging capabilities compared to Unity's default logging system. We have created a custom sink (UnityConsoleSink) to redirect Serilog logs to Unity's console.

Setup

  1. Add Serilog to Your Project: Ensure that Serilog is added to your Unity project. You can do this via NuGet or by directly adding the Serilog DLLs.

  2. Custom Sink (UnityConsoleSink): We have a custom sink implementation that forwards logs to Unity's Debug.Log. This is defined in UnityConsoleSink.cs.

  3. LogManager Setup: In LogManager.cs, Serilog is configured to use our custom sink. The LogManager component should be added to a GameObject in your Unity scene to initialize logging at the start.

Usage

  • Basic Logging: Use Serilog's static Log class to log messages. For example, Log.Information("This is an information message.");
  • Changing Log Levels: You can adjust the minimum log level in LogManager.cs. By default, it's set to .MinimumLevel.Warning(), which means only warnings and errors are logged. Adjust this level based on your needs.

Customizing Log Format

  • Modify UnityConsoleSink.Emit method to change how logs appear in Unity's console. The current format is [.NET API] {message}.

Adapting to Different Environments

  • If your code runs both inside and outside Unity, use preprocessor directives (#if UNITY_EDITOR || UNITY_STANDALONE) in LogManager.cs to switch between UnityConsole and other Serilog sinks (e.g., console, file).

Example Code

// LogManager.cs
using Serilog;

public class LogManager : MonoBehaviour
{
    void Awake()
    {
        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Warning()
            .WriteTo.UnityConsole()
            .CreateLogger();
    }
}

// UnityConsoleSink.cs
using Serilog.Core;
using Serilog.Events;
using UnityEngine;

public class UnityConsoleSink : ILogEventSink
{
    public void Emit(LogEvent logEvent)
    {
        Debug.Log($"[.NET API] {logEvent.RenderMessage()}");
    }
}

public static class UnityConsoleSinkExtensions
{
    public static LoggerConfiguration UnityConsole(
        this LoggerSinkConfiguration loggerConfiguration)
    {
        return loggerConfiguration.Sink(new UnityConsoleSink());
    }
}

Conclusion

This setup allows you to leverage Serilog's advanced logging features in Unity, enhancing debugging and development efficiency. Feel free to customize the logging configuration and format to suit your project's needs.

Clone this wiki locally