2

好的,所以我正在尝试 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 方法) 。我要给你们两个投票。谢谢和抱歉。

4

2 回答 2

2

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

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

ctor 类中实际发生的事情GetBlogFeeds- 从堆栈跟踪来看,您似乎在调用UserDetails特定用户,这在类ctor似乎有点奇怪。

于 2010-12-29T20:17:06.337 回答
1

Why are you returning null when the exception happens?

Based on the posted exception its because of a null exception, it also of course might be the fact your attempting to log the entire Exception object instead of its Message.

Be sure if you agree with this answer to mark it as the answer. If you have additional question with regards to the posted error I can answer them. Without more information ( for example ) where exactly the error is happening in your code I couldn't provide more information.

I just pointed out two odd behaviors.

于 2010-12-29T18:22:20.993 回答