青春须早为,岂能长少年。这篇文章主要讲述log4net 控制台和文件和数据库输出三种方式相关的知识,希望能为你提供帮助。
1、新建console应用项目SendEvaluateDataToProvinceConsole
2、选择SendEvaluateDataToProvinceConsole项目右键 选择 管理NuGet程序包,搜索log4net ,点击安装
3、选择SendEvaluateDataToProvinceConsole项目右键 新建App.config,App.config添加一下内容
< ?xml version="1.0" encoding="utf-8"?>
< configuration>
< configSections>
< !-- log4net的定义配置节 -->
< section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
< /configSections>
< log4net>
< !--日志保存到文件里面Log.txt-->
< appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
< param name="File" value="https://www.songbingjia.com/android/Log//Log.txt"/>
< param name="AppendToFile" value="https://www.songbingjia.com/android/true"/>
< param name="MaxSizeRollBackups" value="https://www.songbingjia.com/android/100"/>
< param name="MaximumFileSize" value="https://www.songbingjia.com/android/2MB"/>
< param name="RollingStyle" value="https://www.songbingjia.com/android/Size"/>
< param name="StaticLogFileName" value="https://www.songbingjia.com/android/true"/>
< !--< param name="Encoding" value="https://www.songbingjia.com/android/utf-8" /> -->
< layout type="log4net.Layout.PatternLayout">
< param name="ConversionPattern" value="https://www.songbingjia.com/android/%-5p %d [%c] %m%n"/>
< /layout>
< /appender>
< !--日志输出到Console-->
< appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
< mapping>
< level value="https://www.songbingjia.com/android/ERROR"/>
< foreColor value="https://www.songbingjia.com/android/White"/>
< backColor value="https://www.songbingjia.com/android/Red,HighIntensity"/>
< /mapping>
< mapping>
< level value="https://www.songbingjia.com/android/DEBUG"/>
< backColor value="https://www.songbingjia.com/android/Green"/>
< /mapping>
< mapping>
< level value="https://www.songbingjia.com/android/Info"/>
< backColor value="https://www.songbingjia.com/android/Yellow"/>
< /mapping>
< layout type="log4net.Layout.PatternLayout">
< conversionPattern value="https://www.songbingjia.com/android/%date [%thread] %-5level %logger [%propertyNDC] - %message%newline"/>
< /layout>
< filter type="log4net.Filter.LevelRangeFilter">
< param name="LevelMin" value="https://www.songbingjia.com/android/Debug"/>
< param name="LevelMax" value="https://www.songbingjia.com/android/Fatal"/>
< /filter>
< /appender>
< !--日志输出到数据库-->
< appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
< !--数据表创建脚本-->
< !--CREATE TABLE LOG(Id integer primary KEY AUTOINCREMENT,Date datetime NOT NULL,UserId varchar(20) NOT NULL,UserName varchar(50) NOT NULL,Message varchar(4000) NOT NULL,Exception varchar(2000) NULL); -->
< !--日志缓存写入条数-->
< !--bufferSize表示批处理的日志事件,可以避免每次日志事件都访问数据库,原本是< bufferSize value="https://www.songbingjia.com/android/100" /> 一百条才插入-->
< bufferSize value="https://www.songbingjia.com/android/1"/>
< !--日志数据库连接串-->
< connectionType value="https://www.songbingjia.com/android/System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
< connectionString value="https://www.songbingjia.com/android/DATABASE=EvMS; SERVER=192.168.1.234; UID=evms; PWD=123456; Connect Timeout=15;" />
< !--System.Data.SQLite, Version=1.0.65.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139-->
< !--< connectionType value="https://www.songbingjia.com/android/System.Data.SQLite.SQLiteConnection, System.Data, Version=1.0.65.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139"/> -->
< !--< connectionString value="https://www.songbingjia.com/android/Data source=F://Person//Longteng//LongtengSln//SendEvaluateDataToProvinceConsole//Data//mysqlite.db; Connect Timeout=15"/> -->
< !--日志数据库脚本-->
< commandText value="https://www.songbingjia.com/android/INSERT INTO LOG([Date],[UserId],[UserName],[Message],[Exception]) VALUES (@Date,@UserId,@UserName,@Message,@Exception)"/>
< !--日志时间Date -->
< parameter>
< parameterName value="https://www.songbingjia.com/android/@Date"/>
< dbType value="https://www.songbingjia.com/android/DateTime"/>
< layout type="log4net.Layout.RawTimeStampLayout"/>
< /parameter>
< !--自定义UserId -->
< parameter>
< parameterName value="https://www.songbingjia.com/android/@UserId"/>
< dbType value="https://www.songbingjia.com/android/String"/>
< size value="https://www.songbingjia.com/android/20"/>
< layout type="log4net.Layout.PatternLayout"/>
< /parameter>
< !--自定义UserName -->
< parameter>
< parameterName value="https://www.songbingjia.com/android/@UserName"/>
< dbType value="https://www.songbingjia.com/android/String"/>
< size value="https://www.songbingjia.com/android/50"/>
< layout type="log4net.Layout.PatternLayout"/>
< /parameter>
< !--日志信息Message -->
< parameter>
< parameterName value="https://www.songbingjia.com/android/@Message"/>
< dbType value="https://www.songbingjia.com/android/String"/>
< size value="https://www.songbingjia.com/android/4000"/>
< layout type="log4net.Layout.PatternLayout"/>
< /parameter>
< !--异常信息Exception -->
< parameter>
< parameterName value="https://www.songbingjia.com/android/@Exception"/>
< dbType value="https://www.songbingjia.com/android/String"/>
< size value="https://www.songbingjia.com/android/2000"/>
< layout type="log4net.Layout.PatternLayout"/>
< /parameter>
< /appender>
< root>
< level value="https://www.songbingjia.com/android/all"/>
< appender-ref ref="RollingLogFileAppender"/>
< appender-ref ref="ColoredConsoleAppender"/>
< appender-ref ref="AdoNetAppender"/>
< /root>
< /log4net>
< startup>
< supportedRuntime version="v2.0.50727"/>
< /startup>
< /configuration>
4、Program.cs中添加代码
using log4net;
using System;
using System.Reflection;
namespace SendEvaluateDataToProvinceConsole
class Program
/// < summary>
/// 记录日志的日志对象
/// < /summary>
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、运行结果
【log4net 控制台和文件和数据库输出三种方式】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 = https://www.songbingjia.com/android/string.Empty;
PropertyInfo propertyInfo = loggingEvent.MessageObject.GetType().GetProperty(property);
if (propertyInfo != null)
propertyvalue = https://www.songbingjia.com/android/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配置文件如下
< ?xml version="1.0" encoding="utf-8"?>
< configuration>
< configSections>
< !-- log4net的定义配置节 -->
< section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
< /configSections>
< log4net>
< !--日志保存到文件里面Log.txt-->
< appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
< param name="File" value="https://www.songbingjia.com/android/Log//Log.txt"/>
< param name="AppendToFile" value="https://www.songbingjia.com/android/true"/>
< param name="MaxSizeRollBackups" value="https://www.songbingjia.com/android/100"/>
< param name="MaximumFileSize" value="https://www.songbingjia.com/android/2MB"/>
< param name="RollingStyle" value="https://www.songbingjia.com/android/Size"/>
< param name="StaticLogFileName" value="https://www.songbingjia.com/android/true"/>
< !--< param name="Encoding" value="https://www.songbingjia.com/android/utf-8" /> --> //注释掉,使用下面的自定义转换SendEvaluateDataToProvinceConsole.MyLayout,下面的同理
< layout type="log4net.Layout.PatternLayout">
< param name="ConversionPattern" value="https://www.songbingjia.com/android/%-5p %d [%c] %m%n"/>
< /layout>
< /appender>
< !--日志输出到Console-->
< appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
< mapping>
< level value="https://www.songbingjia.com/android/ERROR"/>
< foreColor value="https://www.songbingjia.com/android/White"/>
< backColor value="https://www.songbingjia.com/android/Red,HighIntensity"/>
< /mapping>
< mapping>
< level value="https://www.songbingjia.com/android/DEBUG"/>
< backColor value="https://www.songbingjia.com/android/Green"/>
< /mapping>
< mapping>
< level value="https://www.songbingjia.com/android/Info"/>
< backColor value="https://www.songbingjia.com/android/Yellow"/>
< /mapping>
< layout type="log4net.Layout.PatternLayout">
< conversionPattern value="https://www.songbingjia.com/android/%date [%thread] %-5level %logger [%propertyNDC] - %message%newline"/>
< /layout>
< filter type="log4net.Filter.LevelRangeFilter">
< param name="LevelMin" value="https://www.songbingjia.com/android/Debug"/>
< param name="LevelMax" value="https://www.songbingjia.com/android/Fatal"/>
< /filter>
< /appender>
< !--日志输出到数据库-->
< appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
< !--数据表创建脚本-->
< !--CREATE TABLE LOG(Id integer primary KEY AUTOINCREMENT,Date datetime NOT NULL,UserId varchar(20) NOT NULL,UserName varchar(50) NOT NULL,Message varchar(4000) NOT NULL,Exception varchar(2000) NULL); -->
< !--日志缓存写入条数-->
< !--bufferSize表示批处理的日志事件,可以避免每次日志事件都访问数据库,原本是< bufferSize value="https://www.songbingjia.com/android/100" /> 一百条才插入-->
< bufferSize value="https://www.songbingjia.com/android/1"/>
< !--日志数据库连接串-->
< connectionType value="https://www.songbingjia.com/android/System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
< connectionString value="https://www.songbingjia.com/android/DATABASE=EvMS; SERVER=192.168.1.234; UID=evms; PWD=123456; Connect Timeout=15;" />
< !--System.Data.SQLite, Version=1.0.65.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139-->
< !--< connectionType value="https://www.songbingjia.com/android/System.Data.SQLite.SQLiteConnection, System.Data, Version=1.0.65.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139"/> -->
< !--< connectionString value="https://www.songbingjia.com/android/Data source=F://Person//Longteng//LongtengSln//SendEvaluateDataToProvinceConsole//Data//mysqlite.db; Connect Timeout=15"/> -->
< !--日志数据库脚本-->
< commandText value="https://www.songbingjia.com/android/INSERT INTO LOG([Date],[UserId],[UserName],[Message],[Exception]) VALUES (@Date,@UserId,@UserName,@Message,@Exception)"/>
< !--日志时间Date -->
< parameter>
< parameterName value="https://www.songbingjia.com/android/@Date"/>
< dbType value="https://www.songbingjia.com/android/DateTime"/>
< layout type="log4net.Layout.RawTimeStampLayout"/>
< /parameter>
< !--自定义UserId -->
< parameter>
< parameterName value="https://www.songbingjia.com/android/@UserId"/>
< dbType value="https://www.songbingjia.com/android/String"/>
< size value="https://www.songbingjia.com/android/20"/>
< !--< layout type="log4net.Layout.PatternLayout"/> -->
< layout type="SendEvaluateDataToProvinceConsole.MyLayout">
< conversionPattern value="https://www.songbingjia.com/android/%PropertyUserId" />
< /layout>
< /parameter>
< !--自定义UserName -->
< parameter>
< parameterName value="https://www.songbingjia.com/android/@UserName"/>
< dbType value="https://www.songbingjia.com/android/String"/>
< size value="https://www.songbingjia.com/android/50"/>
< !--< layout type="log4net.Layout.PatternLayout"/> -->
< layout type="SendEvaluateDataToProvinceConsole.MyLayout">
< conversionPattern value="https://www.songbingjia.com/android/%PropertyUserName" />
< /layout>
< /parameter>
< !--日志信息Message -->
< parameter>
< parameterName value="https://www.songbingjia.com/android/@Message"/>
< dbType value="https://www.songbingjia.com/android/String"/>
< size value="https://www.songbingjia.com/android/4000"/>
< !--< layout type="log4net.Layout.PatternLayout"/> -->
< layout type="SendEvaluateDataToProvinceConsole.MyLayout">
< conversionPattern value="https://www.songbingjia.com/android/%PropertyMessage" />
< /layout>
< /parameter>
< !--异常信息Exception -->
< parameter>
< parameterName value="https://www.songbingjia.com/android/@Exception"/>
< dbType value="https://www.songbingjia.com/android/String"/>
< size value="https://www.songbingjia.com/android/2000"/>
< !--< layout type="log4net.Layout.PatternLayout"/> -->
< !--< layout type="log4net.Layout.ExceptionLayout" /> -->
< layout type="SendEvaluateDataToProvinceConsole.MyLayout">
< conversionPattern value="https://www.songbingjia.com/android/%PropertyException" />
< /layout>
< /parameter>
< /appender>
< root>
< level value="https://www.songbingjia.com/android/all"/>
< appender-ref ref="RollingLogFileAppender"/>
< appender-ref ref="ColoredConsoleAppender"/>
< appender-ref ref="AdoNetAppender"/>
< /root>
< /log4net>
< startup>
< supportedRuntime version="v2.0.50727"/>
< /startup>
< /configuration>
在运行的话数据库中的运行结果如下:
龙腾一族至尊龙骑
推荐阅读
- C# System.Web.Mail.MailMessage 发邮件
- windows不回应ping的原因
- windows提示无法验证数字签名,无法正常进入操作系统
- 保姆级教程,自建公网可访问的Git私有仓库
- nginx 虚拟主机 安装Discuz论坛
- OLEDB和ODBC的区别(优缺点)
- nginx 域名重定向
- C#ShowCursor光标的显示与隐藏
- DirectX 3D 之C#开发