我正在开发.Net Core 2.2和MySQL。 应用程序的常规日志使用NLog登录到数据库,但是我只想将 DB错误(如果在登录时发生)记录到文件中。
如何使用UserID等自定义字段来捕获到文件的数据库连接失败??
这是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"
autoReload="true"
throwExceptions="false"
internalLogLevel="Warn"
internalLogFile="D:\logs\New\internal-nlog.txt">
<targets>
<target name="database" xsi:type="Database"
dbProvider="MySql.Data.MySqlClient.MySqlConnection, MySql.Data"
connectionString="${var:myConnectionstring}">
<commandText>
insert into log (
Logged, Message,
CallSite, Exception, userID
) values (
@Logged, @Message,
@Callsite, @Exception, @userID
);
</commandText>
<parameter name="@logged" layout="${date}" />
<parameter name="@message" layout="${message}" />
<parameter name="@callSite" layout="${event-properties:Callsite}" />
<parameter name="@exception" layout="${exception:tostring}" />
<parameter name="@userID" layout="${event-properties:userID}" />
</target>
</targets>
<rules>
<logger name="*" level="Error" writeTo="database" />
</rules>
</nlog>
在.Net核心中,我这样写:
Logger logger = LogManager.GetCurrentClassLogger();
LogManager.Configuration.Variables["myConnectionstring"]=Setting.connString;
LogManager.ReconfigExistingLoggers();
logger.SetProperty("userID", "UR0001");
logger.SetProperty("Callsite", ex.Error.TargetSite.Name);
logger.LogException(NLog.LogLevel.Error, ex.Error.Message,ex.Error);