How can I use log4net with Unity3d so that log output goes to the editor console and is logged to file? Unity doesn't seem to be able to use an App.config, so the configuration needs to be done in code, but how do I write to the unity console when using log4net?
First add a reference to the log4net
dll in the Unity editor. You can do this by placing the log4net dlls into the Assets/Plugins
directory, or in a child directory of the Assets/Plugins/
directory.
Once log4net
is referenced, you now need to setup the appenders so that log4net knows how to actually start logging. This is what I have for my configuration:
/// <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);
}
This sets up log4net for logging to Logs\EventLog.txt
and to unity's console logging, via the UnityAppender
class. The UnityAppender
class looks like so (I have it as a private inner class):
/// <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);
}
}
}
Then, be sure to call ConfigureAllLogging()
somewhere where you know it will be called. I have it set in a static constructors of one of my global MonoBehavoirs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With