gpt4 book ai didi

c# - NLog LoggerFactory 中的 TypeInitializationException

转载 作者:太空宇宙 更新时间:2023-11-03 22:44:05 25 4
gpt4 key购买 nike

我开发了一个使用 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 本身正在从 System.Configuration 类中获取异常,如所见来自 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 (XML) 配置中存在配置错误。

那你为什么得到一个TypeInitializationException而不是有用的消息?那是因为您在启动程序之前初始化了 NLog。线路:

static readonly Logger logger = LogManager.GetLogger(typeof(App).FullName);

将在 Main 之前运行因为它是一个静态字段。不幸的是,NLog 无法抛出更好的异常(参见:Better TypeInitializationException (innerException is also null))

建议:在这种情况下,建议使用非静态记录器,或者 static Lazy<Logger> :

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

关于c# - NLog LoggerFactory 中的 TypeInitializationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50800113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com