如何将log4net与Unity3d一起使用,以便日志输出进入编辑器控制台并记录到文件中? Unity似乎无法使用App.config,因此配置需要在代码中完成,但在使用log4net时如何写入Unity控制台?
首先在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);
}
这将通过UnityAppender
类设置log4net以记录到Logs\\EventLog.txt
和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);
}
}
}
然后,确保在您知道将调用它的地方调用ConfigureAllLogging()
。 我把它设置在我的一个全球MonoBehavoirs的静态构造函数中。