需三个步骤:
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
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">
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}" />
name="log_database"
xsi:type="Database"
connectionString="Data Source=.;Initial Catalog=数据库名;Persist Security Info=True;User ID=sa;Password=密码">
insert into NLogInfo([Date],[origin],[Level],[Message],[Detail]) values (getdate(), @origin, @logLevel, @message,@detail);
3、调用
private Logger logger = LogManager.GetCurrentClassLogger();