Net Nlog 持久化到数据库
1.添加Nuget: NLog
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="Off" internalLogFile="c:\temp\nlog-internal.log"> <variable name="myvar" value="myvalue"/> <targets> <target xsi:type="Database" name="rollfile_trace_db" connectionString="Data Source=xxx;Initial Catalog=xxx;User Id=xxx;Password=xxx"> <commandText> insert into Setting_Log([Code], [AddTime], [AddUser], [ControllerName], [ActionName], [Remark]) values (@Code, @AddTime, @AddUser, @ControllerName, @ActionName, @Remark); </commandText> <!--日志主键,添加时间,添加人--> <parameter name="@Code" layout="${event-properties:Code}"/> <parameter name="@AddTime" layout="${event-properties:AddTime}"/> <parameter name="@AddUser" layout="${event-properties:AddUser}"/> <!--触发控制器名,Action--> <parameter name="@ControllerName" layout="${event-properties:ControllerName}"/> <parameter name="@ActionName" layout="${event-properties:ActionName}"/> <!--日志信息--> <parameter name="@Remark" layout="${event-properties:Remark}"/> </target> </targets> <rules> <!--所有 Trace 等级日志会记录到DB,禁止设置其他 Trace 等级日志--> <logger name="*" level="Trace" writeTo="rollfile_trace_db" /> </rules> </nlog>
2.1.配置参数
allowDbNull="true" -- 允许为空
3.后端配置Nlog参数
/// <summary> /// 日志记录到数据库 /// </summary> /// <param name="code"></param> /// <param name="controllerName"></param> /// <param name="actionName"></param> /// <param name="remark"></param> public void Log(string code, string controllerName, string actionName, string remark) { var ei = new LogEventInfo(); ei.Properties["Code"] = code; ei.Properties["AddTime"] = DateTimeExtend.GetValidDate.ToLongString(); ei.Properties["AddUser"] = AuthTiketHelper.GetPersonNo(); ei.Properties["ControllerName"] = controllerName; ei.Properties["ActionName"] = actionName; ei.Properties["Remark"] = remark; ei.Level = LogLevel.Trace; _logger.Log(ei); }