Nlog寫入到數據庫


需三個步驟:

1、創建表

CREATE TABLE [dbo].[NLogInfo](
[LogId] [int] IDENTITY(1,1) NOT NULL,
[Date] [datetime] NOT NULL,
[Origin] [nvarchar](100) NULL,
[Level] [nvarchar](50) NULL,
[Message] [nvarchar](max) NULL,
[Detail] [nvarchar](max) NULL,
) ON [PRIMARY]

2、配置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="Trace" internalLogFile="Nlog.log">

<variable name="variable1"
value="
${newline} date: ${date}
${newline}level: ${level}
${newline}logger: ${logger}
${newline}machinename: ${machinename}
${newline}message: ${message}
${newline}appdomain: ${appdomain}
${newline}assembly-version: ${assembly-version}
${newline}basedir: ${basedir}
${newline}callsite: ${callsite}
${newline}callsite-linenumber: ${callsite-linenumber}
${newline}counter: ${counter}
${newline}nlogdir: ${nlogdir}
${newline}processid: ${processid}
${newline}processname: ${processname}
${newline}specialfolder: ${specialfolder}
${newline}stacktrace: ${stacktrace}${newline}" />

<targets>
<!-- <target name="log_file"
xsi:type="File"
fileName="${basedir}/LogInformation/${level}_${shortdate}.txt"
layout="${variable1}" />-->

<target
name="log_database"
xsi:type="Database"
connectionString="Data Source=.;Initial Catalog=數據庫名;Persist Security Info=True;User ID=sa;Password=密碼">
<commandText>
insert into NLogInfo([Date],[origin],[Level],[Message],[Detail]) values (getdate(), @origin, @logLevel, @message,@detail);
</commandText>
<!--日志來源-->
<parameter name="@origin" layout="${callsite}" />
<!--日志等級-->
<parameter name="@logLevel" layout="${level}" />
<!--日志消息-->
<parameter name="@message" layout="${message}" />
<!--引用variable1信息-->
<parameter name="@detail" layout="${variable1}" />
</target>
</targets>

<rules>
<!--<logger name="*" writeTo="log_file" />-->
<logger name="*" writeTo="log_database" />
</rules>
</nlog>

 

 3、調用

private Logger logger = LogManager.GetCurrentClassLogger();


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM