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

时间:2014-05-22 01:27:23

标签: .net unity3d log4net

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

1 个答案:

答案 0 :(得分:12)

首先在Unity编辑器中添加对log4net 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);
}

这将通过Logs\EventLog.txt类设置log4net以记录到UnityAppender和统一控制台日志记录。 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);
    }
  }
}

然后,请务必在您知道将被调用的地方调用ConfigureAllLogging()。我把它设置在我的一个全球MonoBehavoirs的静态构造函数中。