log4net保存到数据库系列四、完整代码配置log4net

园子里面有很多关于log4net保存到数据库的帖子,但是要动手操作还是比较不易,从头开始学习log4net数据库日志一、WebConfig中配置log4net

下面先一点一点来学习如果进行配置

1.下载,2.数据库脚本,请参考log4net保存到数据库系列一:WebConfig中配置log4net

3.代码

ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString());

AdoNetAppender adoNetAppender = new AdoNetAppender();
adoNetAppender.BufferSize = -1;
adoNetAppender.ConnectionType = "System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
adoNetAppender.ConnectionString = "data source=[服务器地址];initial catalog=[数据库];persist security info=True;user id=[账号];password=[密码];MultipleActiveResultSets=True;";
adoNetAppender.CommandText = "INSERT INTO Logs ([Date],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @log_level, @logger, @Message, @exception)";
adoNetAppender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@log_date", DbType = System.Data.DbType.DateTime, Layout = new log4net.Layout.RawTimeStampLayout() });
adoNetAppender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@log_level", DbType = System.Data.DbType.String, Size = 50, Layout = new Layout2RawLayoutAdapter(new PatternLayout("%level")) });
adoNetAppender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@logger", DbType = System.Data.DbType.String, Size = 255, Layout = new Layout2RawLayoutAdapter(new PatternLayout("%logger")) });
adoNetAppender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@message", DbType = System.Data.DbType.String, Size = 4000, Layout = new Layout2RawLayoutAdapter(new PatternLayout("%message")) });
adoNetAppender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@exception", DbType = System.Data.DbType.String, Size = 4000, Layout = new Layout2RawLayoutAdapter(new ExceptionLayout()) });
adoNetAppender.ActivateOptions();
BasicConfigurator.Configure(rep, adoNetAppender); ILog log = LogManager.GetLogger(rep.Name, "jimLogger"); log.Info("测试")

4.测试成功

log4net保存到数据库系列四、完整代码配置log4net

上一篇:C# 在项目中配置Log4net


下一篇:IIS------无法打开登录所请求的数据库 "company"。登录失败。 用户 'IIS APPPOOL\AppPool 4.0' 登录失败。