世界热议:Nlog-动态修改DatabaseTarget,对数据库字符串进行加密
来源:博客园
2023-04-18 16:01:10
【资料图】
private static Logger processLogger; // ① LnProcessDBLog标签 LogManager.GetLogger("LnProcessDBLog");②使用前先保证不为null,否则InitNlog(); // 修改Nlog.config配置的文件 private static void InitNlog() { LoggingConfiguration loggingConfiguration = NLog.LogManager.Configuration; var rule = loggingConfiguration.LoggingRules.Where(a => a.LoggerNamePattern == "LnProcessDBLog")?.FirstOrDefault(); // 方式一: //var targetDB = rule.target....FirstOrDefault() ; // 找到DatabaseTarget;不能转化为DatabaseTarget //targetDB.con // 找不到类型且找到也不可修改,只有get属性 // 方式二:先删除再添加新的 if (rule != null) { loggingConfiguration.LoggingRules.Remove(rule); // 移除原来的DatabaseTarget配置 } var logDatabase = new NLog.Targets.DatabaseTarget("LnProcessDBLog"); logDatabase.DBProvider = "System.Data.SqlClient"; // 使用的连接类库 string _connectionString = ConfigurationManager.AppSettings["DefaultConnection"]; // 加密的连接字符串 logDatabase.ConnectionString = AESEncryptHelper.Decode(_connectionString); // 解密连接字符串 logDatabase.CommandType = CommandType.Text; // 默认为CommandType.Text logDatabase.CommandText = @"INSERT INTO [SYS_LOG_DETAILS]([LogDate],[LogThread],[LogLevel],[LogLogger],[LogMessage],[LogActionClick],[UserName],[UserIP],[LogOrder]) VALUES(@LogDate,@LogThread,@LogLevel,@LogLogger,@LogMessage,@LogActionClick,@UserName,@UserIP,@LogOrder)"; logDatabase.Parameters.Add(new DatabaseParameterInfo() { Name = "@LogDate", Layout = "${event-properties:item=LogDate}" }); logDatabase.Parameters.Add(new DatabaseParameterInfo() { Name = "@LogThread", Layout = "${event-properties:item=LogThread}" }); logDatabase.Parameters.Add(new DatabaseParameterInfo() { Name = "@LogLevel", Layout = "${event-properties:item=LogLevel}" }); logDatabase.Parameters.Add(new DatabaseParameterInfo() { Name = "@LogLogger", Layout = "${event-properties:item=LogLogger}" }); logDatabase.Parameters.Add(new DatabaseParameterInfo() { Name = "@LogMessage", Layout = "${event-properties:item=LogMessage}" }); logDatabase.Parameters.Add(new DatabaseParameterInfo() { Name = "@LogActionClick", Layout = "${event-properties:item=LogActionClick}" }); logDatabase.Parameters.Add(new DatabaseParameterInfo() { Name = "@LogOrder", Layout = "测试" }); logDatabase.Parameters.Add(new DatabaseParameterInfo() { Name = "@UserName", Layout = "${event-properties:item=UserName}" }); logDatabase.Parameters.Add(new DatabaseParameterInfo() { Name = "@UserIP", Layout = "${event-properties:item=UserIP}" }); loggingConfiguration.AddRule(LogLevel.Trace, LogLevel.Fatal, logDatabase, "LnProcessDBLog", true); // 添加新的DatabaseTarget配置 NLog.LogManager.Configuration = loggingConfiguration; // 赋值给NLog.LogManager.Configuration。 processLogger = LogManager.GetLogger("LnProcessDBLog"); // 重新给全局变量赋值。 }