[.Net Core] - 使用 NLog 记录日志到 Sql Server

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

posted @   jinzesudawei  阅读(380)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示