1、新建console应用项目SendEvaluateDataToProvinceConsole
2、选择SendEvaluateDataToProvinceConsole项目右键 选择 管理NuGet程序包,搜索log4net ,点击安装
3、选择SendEvaluateDataToProvinceConsole项目右键 新建App.config,App.config添加一下内容
"1.0" encoding="utf-8"?>"log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> "RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> "File" value="Log\Log.txt"/> "AppendToFile" value="true"/> "MaxSizeRollBackups" value="100"/> "MaximumFileSize" value="2MB"/> "RollingStyle" value="Size"/> "StaticLogFileName" value="true"/> "log4net.Layout.PatternLayout"> "ConversionPattern" value="%-5p %d [%c] %m%n"/> "ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender"> "ERROR"/> "White"/> "Red,HighIntensity"/> "DEBUG"/> "Green"/> "Info"/> "Yellow"/> "log4net.Layout.PatternLayout"> "%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"/> "log4net.Filter.LevelRangeFilter"> "LevelMin" value="Debug"/> "LevelMax" value="Fatal"/> "AdoNetAppender" type="log4net.Appender.AdoNetAppender"> "1"/> "System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> "DATABASE=EvMS;SERVER=192.168.1.234;UID=evms;PWD=123456;Connect Timeout=15;" /> "INSERT INTO LOG([Date],[UserId],[UserName],[Message],[Exception]) VALUES (@Date,@UserId,@UserName,@Message,@Exception)"/> "@Date"/> "DateTime"/> "log4net.Layout.RawTimeStampLayout"/> "@UserId"/> "String"/> "20"/> "log4net.Layout.PatternLayout"/> "@UserName"/> "String"/> "50"/> "log4net.Layout.PatternLayout"/> "@Message"/> "String"/> "4000"/> "log4net.Layout.PatternLayout"/> "@Exception"/> "String"/> "2000"/> "all"/> ref ref="RollingLogFileAppender"/> ref ref="ColoredConsoleAppender"/> ref ref="AdoNetAppender"/> "v2.0.50727"/>
4、Program.cs中添加代码
using log4net; using System; using System.Reflection; namespace SendEvaluateDataToProvinceConsole { class Program { ////// 记录日志的日志对象 /// public static ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); static void Main(string[] args) { //log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(@"F:\Person\Longteng\LongtengSln\SendEvaluateDataToProvince\App.config")); log4net.Config.XmlConfigurator.Configure();//这一句很重要。。。。。 try { Log.Info("123..."); Log.Info("普通日志"); Log.Error("错误日志"); Log.Debug("异常信息"); Log.Fatal("致命错误"); Log.Warn("警告信息"); LogEntity logEntity = new LogEntity { //Id= "123", UserId = "123", UserName = "张三", Message = "消息西夏熊", Exception = "Exception" }; Log.Debug(logEntity); Console.Read(); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.Source); Console.WriteLine(e.StackTrace); Console.WriteLine(e.InnerException != null ? e.InnerException.ToString() : ""); Console.ReadLine(); } } } }
5、运行结果
6、上图运行结果注意有些数据不太对,就是插入的是LogEntity 对象,显示的就是一个对象,而不是对象具体对应的数据
LogEntity logEntity = new LogEntity
{
//Id= "123",
UserId = "123",
UserName = "张三",
Message = "消息西夏熊",
Exception = "Exception"
};
分析原因是因为LogEntity 是自定义的对象,log4net并不知道LogEntity 是什么东西,所以我们转换一下,把LogEntity 转换成log4net认识的对象就可以了,其实就是修改显示的log4net模式PatternLayout,
代码如下:
先建MyPatternConverter类,继承log4net的PatternLayoutConverter类
using log4net.Core; using log4net.Layout.Pattern; using System.IO; using System.Reflection; namespace SendEvaluateDataToProvinceConsole { public class MyPatternConverter : PatternLayoutConverter { protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) { if (Option != null) WriteObject(writer, loggingEvent.Repository, LookupProperty(Option, loggingEvent)); else WriteDictionary(writer, loggingEvent.Repository, loggingEvent.GetProperties()); } //通过反射获取传入的日志对象的某个属性的值 private object LookupProperty(string property, log4net.Core.LoggingEvent loggingEvent) { object propertyvalue = string.Empty; PropertyInfo propertyInfo = loggingEvent.MessageObject.GetType().GetProperty(property); if (propertyInfo != null) propertyvalue = propertyInfo.GetValue(loggingEvent.MessageObject, null); return propertyvalue; } } }
再新建MyLayout类,继承log4net的PatternLayout类
using log4net.Layout; namespace SendEvaluateDataToProvinceConsole { public class MyLayout : PatternLayout { public MyLayout() { this.AddConverter("Property", typeof(MyPatternConverter)); } } }
上面建好MyPatternConverter类和MyLayout类以后,修改App.config配置文件如下
"1.0" encoding="utf-8"?>"log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> "RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> "File" value="Log\Log.txt"/> "AppendToFile" value="true"/> "MaxSizeRollBackups" value="100"/> "MaximumFileSize" value="2MB"/> "RollingStyle" value="Size"/> "StaticLogFileName" value="true"/> //注释掉,使用下面的自定义转换SendEvaluateDataToProvinceConsole.MyLayout,下面的同理 "log4net.Layout.PatternLayout"> "ConversionPattern" value="%-5p %d [%c] %m%n"/> "ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender"> "ERROR"/> "White"/> "Red,HighIntensity"/> "DEBUG"/> "Green"/> "Info"/> "Yellow"/> "log4net.Layout.PatternLayout"> "%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"/> "log4net.Filter.LevelRangeFilter"> "LevelMin" value="Debug"/> "LevelMax" value="Fatal"/> "AdoNetAppender" type="log4net.Appender.AdoNetAppender"> "1"/> "System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> "DATABASE=EvMS;SERVER=192.168.1.234;UID=evms;PWD=123456;Connect Timeout=15;" /> "INSERT INTO LOG([Date],[UserId],[UserName],[Message],[Exception]) VALUES (@Date,@UserId,@UserName,@Message,@Exception)"/> "@Date"/> "DateTime"/> "log4net.Layout.RawTimeStampLayout"/> "@UserId"/> "String"/> "20"/> "SendEvaluateDataToProvinceConsole.MyLayout"> "%Property{UserId}" /> "@UserName"/> "String"/> "50"/> "SendEvaluateDataToProvinceConsole.MyLayout"> "%Property{UserName}" /> "@Message"/> "String"/> "4000"/> "SendEvaluateDataToProvinceConsole.MyLayout"> "%Property{Message}" /> "@Exception"/> "String"/> "2000"/> "SendEvaluateDataToProvinceConsole.MyLayout"> "%Property{Exception}" /> "all"/> ref ref="RollingLogFileAppender"/> ref ref="ColoredConsoleAppender"/> ref ref="AdoNetAppender"/> "v2.0.50727"/>
在运行的话数据库中的运行结果如下: