NLog LoggerFactory

时间:2018-06-11 14:29:13

标签: c# exception nlog typeinitializeexception

我开发了一个使用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];
              //..

1 个答案:

答案 0 :(得分:3)

您的NLog(XML)配置中可能存在配置错误。

那你为什么得到private byte[] createAdtsHeader(int length) { int frameLength = length + 7; byte[] adtsHeader = new byte[7]; adtsHeader[0] = (byte) 0xFF; // Sync Word adtsHeader[1] = (byte) 0xF1; // MPEG-4, Layer (0), No CRC adtsHeader[2] = (byte) ((MediaCodecInfo.CodecProfileLevel.AACObjectLC - 1) << 6); adtsHeader[2] |= (((byte) SAMPLE_RATE_INDEX) << 2); adtsHeader[2] |= (((byte) CHANNELS) >> 2); adtsHeader[3] = (byte) (((CHANNELS & 3) << 6) | ((frameLength >> 11) & 0x03)); adtsHeader[4] = (byte) ((frameLength >> 3) & 0xFF); adtsHeader[5] = (byte) (((frameLength & 0x07) << 5) | 0x1f); adtsHeader[6] = (byte) 0xFC; return adtsHeader; } 而不是有用的信息呢?这是因为你在开始程序之前初始化NLog。这一行:

TypeInitializationException

将在static readonly Logger logger = LogManager.GetLogger(typeof(App).FullName); 之前运行,因为它是一个静态字段。不幸的是,NLog不能抛出更好的例外(参见:Better TypeInitializationException (innerException is also null)

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

static Lazy<Logger>