集成Unity日志输出可以分为两个部分
一、下载log4net和Unity的配置
- 下载log4net dll至Assets目录下的References文件夹中,如下图:
- Unity中File->Build Settings->PlayerSettings->Player中的设置,Api Compatibility Level 设置为.NET 4.x如下图:
二、集成log4net的代码及log4net配置文件
- log4net配置文件名为:log4net.config。文件内容如下:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="System.Configuration.IgnoreSectionHandler"/>
</configSections>
<appSettings>
</appSettings>
<log4net>
<appender name="FileAppender" type="log4net.Appender.RollingFileAppender">
<file type="log4net.Util.PatternString" value="%property{ApplicationLogPath}\\%property{LogFileName}.log" />
<rollingStyle value="Composite" />
<datePattern value="yyyy-MM-dd" />
<staticLogFileName value="false" />
<param name="Encoding" value="utf-8" />
<maximumFileSize value="100MB" />
<countDirection value="0" />
<maxSizeRollBackups value="100" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="记录时间:%date 线程:[%thread] 日志级别:%-5level 记录类:%logger 日志消息:%message%newline" />
</layout>
</appender>
<appender name="UiLogAppender" type="UiLogAppender">
</appender>
<logger name="FileLogger" additivity="false">
<level value="DEBUG" />
<appender-ref ref="FileAppender" />
</logger>
</log4net>
</configuration>
- log4net配置文件位置与Assets同级(也可以放在其他位置,配置文件加载的时候换个路径就行)如下图:
- Unity日志集成类UnityLogger代码如下:
using log4net;
using UnityEngine;
public static class UnityLogger
{
public static void Init() {
Application.logMessageReceived += onLogMessageReceived;
Debug.Log("日志初始化");
}
private static ILog log = LogManager.GetLogger("FileLogger");
private static void onLogMessageReceived(string condition,string stackTrace,LogType type) {
switch (type) {
case LogType.Error:
log.ErrorFormat("{0}\r\n{1}", condition, stackTrace.Replace("\n", "\r\n"));
break;
case LogType.Assert:
log.DebugFormat("{0}\r\n{1}", condition, stackTrace.Replace("\n", "\r\n"));
break;
case LogType.Exception:
log.FatalFormat("{0}\r\n{1}", condition, stackTrace.Replace("\n", "\r\n"));
break;
case LogType.Warning:
log.WarnFormat("{0}\r\n{1}", condition, stackTrace.Replace("\n", "\r\n"));
break;
default:
log.Info(condition);
break;
}
}
}
- 初始化UnityLogger,初始化代码放在整个游戏的一个MonoBehaviour的Start中,代码如下:
void Start()
{
FileInfo file = new System.IO.FileInfo("log4net.config");
GlobalContext.Properties["ApplicationLogPath"] = Path.Combine(file.Directory.FullName,"Log");
GlobalContext.Properties["LogFileName"] = "log";
log4net.Config.XmlConfigurator.ConfigureAndWatch(file);
UnityLogger.Init();
}
- 打包后log4net.config配置文件的位置如下图:
|