2
這是我NLog.config文件:NLOG被寫入文件而不是數據庫表
<?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而不是最後一個寫入所有錯誤。
請啓用[內部記錄(https://github.com/NLog/NLog/wiki/Internal-Logging),以便有更多的信息 –
看到我內部日誌錯誤!感謝@MartinoBordin現在正在寫入數據庫。關於如何編寫所有錯誤而不是最後一個的任何想法? –
如果我正確理解您的需求,您必須使用MVC填充器。看看[這個實現](https://github.com/MikeHanson/NLog.Mvc/wiki/Using-the-NLogMvcHandlEerrorAttribute) –