[.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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探