这是我的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"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="false"
internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log" >
<variable name="myvar" value="myvalue"/>
<targets>
<target name="database" xsi:type="Database"
dbUserName="internwebuser"
dbProvider="System.Data.SqlClient"
connectionStringName="SECURE"
connectionString="Data Source=sqlservtest.starledger.com;Initial Catalog=SECURE;User ID=webuser;Password=password"
commandText="insert into dbo.tracelog (custom_message, excep_message, insertdate)
values
(@custom_message, @excep_message, @insertdate);" >
<parameter name="@custom_message" layout="${exception}" />
<parameter name="@excep_message" layout="${exception:tostring}" />
<parameter name="@insertdate" layout="${date}" />
</target>
<target name="file" xsi:type="File"
layout="${longdate} ${uppercase:${level}} ${callsite} from Line: ${callsite-linenumber} ${newline}
${exception} ${newline}
${exception:tostring} ${newline}"
fileName="${basedir}/logs/${shortdate}-${level}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="file" />
<logger name="*" minlevel="Debug" writeTo="database" />
</rules>
</nlog>
我的控制器看起来像这样:
public class ReportController : Controller
{
private static Logger logger = LogManager.GetCurrentClassLogger();
public ActionResult Index()
{
try
{
<!-- some statement -->
}
catch (Exception e)
{
logger.Error(e);
}
return View();
}
}
此代码完美地写入文件但数据库表仍为空。此外,在我的文件中,当我使用StreamWriter
创建文件而不是使用NLog时,应用程序同时将2/3种错误写入文件。但是NLog只写了最后一个错误。
例如:
如果是StreamWriter
,则错误为:
Exception Name:ExecuteReader requires an open and available Connection. The connection's current state is closed.
Exception Name:Object reference not set to an instance of an object.
但是对于NLog,我只能得到:
Exception Name:Object reference not set to an instance of an object.
and the first one is missed out.
我的StreamWriter
方法如下所示:
DateTime today = DateTime.Now;
string path = Directory.GetCurrentDirectory();
string fileName = "error-log-" + today.Date.ToString("MM-dd-yyyy") + ".txt";
var file = Path.Combine(path, fileName);
StreamWriter log;
if (!File.Exists(file))
{
log = new StreamWriter(file);
}
else
{
log = File.AppendText(file);
}
// Write to the file:
log.WriteLine("Data Time:" + DateTime.Now);
log.WriteLine("Exception Name:" + sExceptionName);
log.WriteLine("Event Name:" + sEventName);
log.WriteLine("Error Line No.:" + nErrorLineNo);
// Close the stream:
log.Close();
我将该方法传递给控制器的catch
部分。
我的主要问题是写入数据库表,虽然我也非常感谢使用Nlog编写所有错误的帮助,而不仅仅是最后一个。
答案 0 :(得分:2)
我遇到了同样的问题。为了找到确切的问题,我在 nlog 标签中添加了 <nlog internalLogFile="c:\DemoLogs\nlog-internal.txt" and internalLogLevel="Error">
。这会将确切的proplem写入日志文件
就我而言,Could not load file or assembly 'System.Data.SqlClient
在我安装该 nuget 包时得到解决。
答案 1 :(得分:1)
请启用internal logging以获取更多信息