C# NLog LoggerFactory中的TypeInitializationException异常

C# NLog LoggerFactory中的TypeInitializationException异常,c#,exception,nlog,typeinitializeexception,C#,Exception,Nlog,Typeinitializeexception,我开发了一个使用NLog的WPF应用程序。它已经部署到了一些潜在客户,其中一个客户的应用程序在一周内运行良好,现在甚至没有打开。也就是说,你双击应用程序图标,实际上什么也没发生。甚至在AppDomain.CurrentDomain.UnhandledExceptioncatch子句中也没有日志记录 我能够在Windows事件查看器中识别事件(请参阅下面的消息) 让我感到困惑的是,经过一周完美的操作后,这个错误突然出现,我无法解释这条消息或在网上找到有关它的信息 Aplicativo: Force

我开发了一个使用NLog的WPF应用程序。它已经部署到了一些潜在客户,其中一个客户的应用程序在一周内运行良好,现在甚至没有打开。也就是说,你双击应用程序图标,实际上什么也没发生。甚至在
AppDomain.CurrentDomain.UnhandledException
catch子句中也没有日志记录

我能够在Windows事件查看器中识别事件(请参阅下面的消息)

让我感到困惑的是,经过一周完美的操作后,这个错误突然出现,我无法解释这条消息或在网上找到有关它的信息

Aplicativo: ForceViewer.exe
Versão do Framework: v4.0.30319
Descrição: O processo foi terminado devido a uma exceção sem tratamento.
Informações da Exceção: System.Xml.XmlException
em System.Xml.XmlTextReaderImpl.Throw(System.Exception)
em System.Xml.XmlTextReaderImpl.ParseDocumentContent()
em System.Xml.XmlTextReaderImpl.Read()
em System.Xml.XmlTextReader.Read()
em System.Configuration.XmlUtil..ctor(System.IO.Stream, System.String, Boolean, System.Configuration.ConfigurationSchemaErrors)
em System.Configuration.BaseConfigurationRecord.InitConfigFromFile()

Informações da Exceção: System.Configuration.ConfigurationErrorsException
em System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean)
em System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(System.Configuration.ConfigurationSchemaErrors)
em System.Configuration.BaseConfigurationRecord.ThrowIfInitErrors()
em System.Configuration.ClientConfigurationSystem.OnConfigRemoved(System.Object, System.Configuration.Internal.InternalConfigEventArgs)

Informações da Exceção: System.Configuration.ConfigurationErrorsException
em System.Configuration.ConfigurationManager.PrepareConfigSystem()
em System.Configuration.ConfigurationManager.get_AppSettings()
em NLog.Common.InternalLogger.GetSettingString(System.String, System.String)
em NLog.Common.InternalLogger.GetSetting[[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]](System.String, System.String, Boolean)
em NLog.Common.InternalLogger.Reset()
em NLog.Common.InternalLogger..cctor()

Informações da Exceção: System.TypeInitializationException
em NLog.Common.InternalLogger.Log(System.Exception, NLog.LogLevel, System.String)
em NLog.Internal.ExceptionHelper.MustBeRethrown(System.Exception)
em NLog.LogFactory.get_Configuration()
em NLog.LogFactory.GetLogger(LoggerCacheKey)
em NLog.LogFactory.GetLogger(System.String)
em NLog.LogManager.GetLogger(System.String)
em Miotec.ForceViewer.App..cctor()

Informações da Exceção: System.TypeInitializationException
em Miotec.ForceViewer.App.Main(System.String[])
这是我的App.xaml.cs:

public partial class App : Application
{
    static string AppName = "ForceViewer 1.1";

    static readonly Mutex mutex = new Mutex(true, AppName);

    // APPARENTLY the exception happens in the line below:
    static readonly Logger logger = LogManager.GetLogger(typeof(App).FullName);


    [STAThread]
    public static void Main(string[] args)
    {
        SplashScreen splashScreen = new SplashScreen("Splash.png");
        splashScreen.Show(true);

        if (mutex.WaitOne(TimeSpan.Zero, true))
        {
            var app = new App();
            app.InitializeComponent();
            app.Run();
            mutex.ReleaseMutex();
        }
        else
        {
            Extensions.EnviaMensagemPraAtivarOutraJanela();
        }
    }


    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        WpfLauncher.Launch(this, new ForceViewerBootstrapper(AppName));
        logger.Info($"Aplicação {AppName} iniciada");
    }
}
更新(包括其他可能的相关信息):

有些人提到NLog XML配置文件,但我使用的是运行时配置,如下所示:

        var dirname = Path.Combine(@"C:\\AppFolder", appName, "logs");

        Directory.CreateDirectory(dirname);

        var filename = Path.Combine(dirname, $"{appName}.log");

        var filetarget = new FileTarget("app")
        {
            FileName = filename,
            Encoding = Encoding.UTF8,
            Layout = "${longdate}|${level:uppercase=true}|${message} (${logger:shortName=true})",
            AutoFlush = true,
            MaxArchiveFiles = 8,
            ArchiveAboveSize = 1048576,
            ArchiveEvery = FileArchivePeriod.Friday,
            ConcurrentWrites = true
        };

        var asyncTarget = new AsyncTargetWrapper("app", filetarget);

        var config = new LoggingConfiguration();
        config.AddRuleForAllLevels(asyncTarget);
        config.AddTarget(asyncTarget);
        LogManager.Configuration = config;
此外,“堆栈跟踪”(在Windows事件的情况下,它似乎是向后打印的)表明NLog本身从
系统中得到了异常。从
InternalLogger
的反编译中可以看出,配置
类:

namespace NLog.Common { //... public static class InternalLogger { //... private static string GetSettingString(string configName, string envName) { // Line below seems to be throwing an exception string str = System.Configuration.ConfigurationManager.AppSettings[configName]; //.. 名称空间NLog.Common { //... 公共静态类内部记录器 { //... 私有静态字符串GetSettingString(字符串configName、字符串envName) { //下面的行似乎抛出了一个异常 string str=System.Configuration.ConfigurationManager.AppSettings[configName]; //..
NLog(XML)配置中可能存在配置错误

那么,为什么会出现
TypeInitializationException
而不是有用的消息呢?这是因为您在启动程序之前初始化了NLog

static readonly Logger logger = LogManager.GetLogger(typeof(App).FullName);
将在
Main
之前运行,因为它是一个静态字段。不幸的是,NLog无法引发更好的异常(请参阅:)

建议:在这种情况下,建议使用非静态记录器,或
静态延迟记录器

static readonly Lazy logger=new Lazy(()=>LogManager.GetLogger(typeof(App.FullName));

您使用的是什么记录器(nlog配置)?可能是某些权限问题导致了这种情况吗?是什么导致了
System.Xml.XmlException
?猜测一下,其中一个Xml配置文件(例如
App.exe.config
)已损坏?@StuartLC我同意这似乎是问题所在。但接下来呢?我想知道是什么原因导致了问题,一方面,另一方面,我不知道该如何纠正/防止。此外,我也不确定该如何调试,因为问题只会在我们只访问的客户端的机器上出现ave远程访问。原因可能是用户篡改、病毒、磁盘故障等,如果fat/智能客户端的风险感谢您的回答。静态延迟记录器,您的意思是这样的?
private static readonly lazy logger=new lazy(()=>LogManager.GetLogger(typeof(App).FullName));
我意识到我没有为NLog使用XML配置,我在代码本身中执行配置(我知道这并不理想,但现在就是这样)。此外,原始异常似乎可能是由.Net类引起的,特别是
System.Configuration.ConfigurationManager.AppSettings
,它引发
ConfigurationErrorsException
(请参阅我的更新)所以你的问题解决了,不是吗?你知道根本原因吗?嗯,事实上不是,但我想这不是NLog故障。我想我必须进一步调查为什么会发生“ConfigurationErrorsException”。无论如何,谢谢你的回答!
static readonly Lazy<Logger> logger = new Lazy<Logger>(() => LogManager.GetLogger(typeof(App).FullName));