我正在将运行了几年的代码从运行Windows 7的计算机移植到Windows10。该项目是使用.NET Framework 4.5.2和NLog 4.4.12的类库。重新编译后,应用程序在构造函数中引发TypeInitializationException。
尝试了以下内容:
引发异常(甚至不输入构造函数):private static NLog.Logger m_nLog = LogManager.GetCurrentClassLogger();
NLog.config:
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="true"
internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
<targets>
<target name="console" xsi:type="Console"
layout = "${time} ${uppercase:${level}} ${message}" />
<target name="logfile" xsi:type="File"
fileName = "${basedir}/Logs/${shortdate}.log"
layout = "${time} ${uppercase:${level}} ${message}" />
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="console" />
<logger name="*" minlevel="Trace" writeTo="logfile" />
</rules>
不知道如何进行或确定内部异常。
答案 0 :(得分:0)
如果NLog中存在问题,例如错误的日志记录配置,NLog可能会引发异常。
如果在构造启动类型之前引发此异常,.NET将使用TypeInitializationException
隐藏该异常(另请参见Better TypeInitializationException (innerException is also null))。
例如在这种情况下:
class Program
{
// this throws a NLogConfigurationException because of bad config. (like invalid XML)
// as this issue will be throw before Main() is called, you will get
// a TypeInitializationException instead of a NLogConfigurationException
private static Logger logger = LogManager.GetCurrentClassLogger();
static void Main()
{
Console.WriteLine("Press any key");
Console.ReadLine();
}
}
3种可能的解决方案:
class Program
{
private static Lazy<Logger> logger = new Lazy<Logger>(() => LogManager.GetCurrentClassLogger());
static void Main()
{
Console.WriteLine("Press any key");
Console.ReadLine();
}
}
class Program
{
private static Logger logger;
static void Main()
{
logger = LogManager.GetCurrentClassLogger();
Console.WriteLine("Press any key");
Console.ReadLine();
}
}
class Program
{
static void Main()
{
private logger = LogManager.GetCurrentClassLogger();
Console.WriteLine("Press any key");
Console.ReadLine();
}
}