1. 使用 Nuget 安装 NLog。
2. 在 Sql Server 中创建 NLog 数据表。
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]
3. 创建并配置 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="Error" internalLogFile="Nlog.log"> <variable name="detailTemplate" 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}exception: ${exception:format=tostring}" /> <targets> <target name="blackhole" xsi:type="Null" /> <target name="database" xsi:type="Database"> <connectionString>${var:connectionString}</connectionString> <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}" /> <parameter name="@detail" layout="${detailTemplate}" /> </target> </targets> <rules> <logger name="*" minlevel="Warn" writeTo="database" /> </rules> </nlog>
4. 在 Startup 中配置 NLog
env.ConfigureNLog("nlog.config"); LogManager.Configuration.Variables["connectionString"] = Configuration.GetConnectionString("DefaultConnection"); loggerFactory.AddNLog();
5. 测试:手工记 Log + 全局异常捕获。
参考资料
https://blog.csdn.net/u013667895/article/details/79067828
https://www.cnblogs.com/chen8854/p/6800158.html
https://stackoverflow.com/questions/5346336/nlog-configuration-across-appdomains