如何使用与Unity一起使用log4net?

Fri*_*Guy 6 .net log4net unity-game-engine

如何将log4net与Unity3d一起使用,以便日志输出进入编辑器控制台并记录到文件中?Unity似乎无法使用App.config,因此配置需要在代码中完成,但在使用log4net时如何写入Unity控制台?

Fri*_*Guy 13

首先log4net在Unity编辑器中添加对dll 的引用.您可以通过将log4net dll放入Assets/Plugins目录或目录的Assets/Plugins/子目录中来完成此操作.

一旦log4net引用,您现在需要设置appender,以便log4net知道如何实际开始记录.这就是我的配置:

/// <summary>
///  Configure logging to write to Logs\EventLog.txt and the Unity console output.
/// </summary>
public static void ConfigureAllLogging()
{
  var patternLayout = new PatternLayout
                      {
                        ConversionPattern = "%date %-5level %logger - %message%newline"
                      };
  patternLayout.ActivateOptions();

  // setup the appender that writes to Log\EventLog.txt
  var fileAppender = new RollingFileAppender
                     {
                       AppendToFile = false,
                       File = @"Logs\EventLog.txt",
                       Layout = patternLayout,
                       MaxSizeRollBackups = 5,
                       MaximumFileSize = "1GB",
                       RollingStyle = RollingFileAppender.RollingMode.Size,
                       StaticLogFileName = true
                     };
  fileAppender.ActivateOptions();

  var unityLogger = new UnityAppender
                    {
                      Layout = new PatternLayout()
                    };
  unityLogger.ActivateOptions();

  BasicConfigurator.Configure(unityLogger, fileAppender);
}
Run Code Online (Sandbox Code Playgroud)

这将Logs\EventLog.txt通过UnityAppender类设置log4net以记录到unity的控制台日志记录.这个UnityAppender类看起来像这样(我把它作为私有内部类):

/// <summary> An appender which logs to the unity console. </summary>
private class UnityAppender : AppenderSkeleton
{
  /// <inheritdoc />
  protected override void Append(LoggingEvent loggingEvent)
  {
    string message = RenderLoggingEvent(loggingEvent);

    if (Level.Compare(loggingEvent.Level, Level.Error) >= 0)
    {
      // everything above or equal to error is an error
      Debug.LogError(message);
    }
    else if (Level.Compare(loggingEvent.Level, Level.Warn) >= 0)
    {
      // everything that is a warning up to error is logged as warning
      Debug.LogWarning(message);
    }
    else
    {
      // everything else we'll just log normally
      Debug.Log(message);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

然后,一定要打电话给ConfigureAllLogging()你知道它会被调用的地方.我把它设置在我的一个全球MonoBehavoirs的静态构造函数中.