c# - NLog 配置错误?

标签 c# nlog

好吧,我正在尝试 NLog,但它总是失败。让我回顾一下到目前为止我所得到的。

我的 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">

    <targets>
      <target name="file" xsi:type="File"
            layout="${longdate} ${logger} ${message}"
            fileName="${basedir}/Logs/${shortdate}.log" />
    </targets>

    <rules>
        <logger name="*" minlevel="Debug" writeTo="file" />
    </rules>
</nlog>

然后我像这样创建我的对象:

private static Logger logger = LogManager.GetCurrentClassLogger();

然后当我想记录一些东西时,我会这样做:

try
{   
    // Do something
}
catch (Exception ex)
{
    logger.Fatal("ERROR {0}", ex);
    return null;
}

但我收到以下错误:

System.TypeInitializationException was unhandled
Message="The type initializer for 'Rhs.CMSSites.Services.GetBlogFeeds' threw an exception."
Source="GetBlogFeeds"
TypeName="Rhs.CMSSites.Services.GetBlogFeeds"
StackTrace:
   at Rhs.CMSSites.Services.GetBlogFeeds.Main(String[] args)
   at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.NullReferenceException
   Message="Object reference not set to an instance of an object."
   Source="GetBlogFeeds"
   StackTrace:
        at Rhs.CMSSites.Services.GetBlogFeeds.UserDetails(String UserName) in C:\Dev\Rhs.CMSSites.Services\GetBlogFeeds\GetBlogFeeds\Program.cs:line 217
        at Rhs.CMSSites.Services.GetBlogFeeds..cctor() in C:\Dev\Rhs.CMSSites.Services\GetBlogFeeds\GetBlogFeeds\Program.cs:line 25
   InnerException: 

有什么想法吗?

编辑

可能应该早点提到这一点,但这是一个命令行应用程序。 GetBlogFeeds 是类的名称。

编辑2

好吧,我真是个白痴。我在实例化记录器类之前调用​​了 UserDetails() 方法(该方法尝试使用 NLog 方法)。我要给你们俩投票。谢谢并抱歉。

最佳答案

我的猜测(确实如此)这与 NLog 无关,而是 TypeInitializationException 如此严重和/或没有在该 的上下文中发生code>try ... catch NLog 没有机会记录它。

如果您在该 logger.Fatal 语句上放置断点,当您在附加调试器的情况下运行时,执行是否会在此处停止?

GetBlogFeeds 的类构造函数中实际发生的情况 - 从堆栈跟踪看来,您为特定用户调用了UserDetails,这在 class ctor 中做这件事似乎有点奇怪。

关于c# - NLog 配置错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4556337/

相关文章:

c# - 如何计算纵向冗余校验 (LRC)?

c# - 获取类成员的默认值

c# - WPF从复选框转换选定值

c# - 何时取消 Hook Xamarin 自定义呈现器中的事件

c# - NLog - 无效的 xsi :type 'http://www.nlog-project.org/schemas/NLog.xsd:AzureAppendBlob'

c# - 缓存在特定时间过期

c# - 如何将 NLog 用于 DLL

asp.net - Nlog 未创建相对于网站项目的文件

c# - 配置 NLog 的布局以显示所有事件上下文条目

c# - 如果日志级别低于阈值,则防止昂贵的日志调用