• 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="LogLog.txt"/>
          <param name="AppendToFile" value="true"/>
          <param name="MaxSizeRollBackups" value="100"/>
          <param name="MaximumFileSize" value="2MB"/>
          <param name="RollingStyle" value="Size"/>
          <param name="StaticLogFileName" value="true"/>
          <!--<param name="Encoding" value="utf-8" />-->
          <layout type="log4net.Layout.PatternLayout">
            <param name="ConversionPattern" value="%-5p %d [%c] %m%n"/>
          </layout>
        </appender>
        <!--日志输出到Console-->
        <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
          <mapping>
            <level value="ERROR"/>
            <foreColor value="White"/>
            <backColor value="Red,HighIntensity"/>
          </mapping>
          <mapping>
            <level value="DEBUG"/>
            <backColor value="Green"/>
          </mapping>
          <mapping>
            <level value="Info"/>
            <backColor value="Yellow"/>
          </mapping>
          <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"/>
          </layout>
          <filter type="log4net.Filter.LevelRangeFilter">
            <param name="LevelMin" value="Debug"/>
            <param name="LevelMax" value="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="100" />一百条才插入-->
          <bufferSize value="1"/>
          <!--日志数据库连接串-->
          <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
          <connectionString value="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="System.Data.SQLite.SQLiteConnection, System.Data, Version=1.0.65.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139"/>-->
          <!--<connectionString value="Data source=F:PersonLongtengLongtengSlnSendEvaluateDataToProvinceConsoleDatamysqlite.db;Connect Timeout=15"/>-->
          <!--日志数据库脚本-->
          <commandText value="INSERT INTO LOG([Date],[UserId],[UserName],[Message],[Exception]) VALUES (@Date,@UserId,@UserName,@Message,@Exception)"/>
          <!--日志时间Date -->
          <parameter>
            <parameterName value="@Date"/>
            <dbType value="DateTime"/>
            <layout type="log4net.Layout.RawTimeStampLayout"/>
          </parameter>
          <!--自定义UserId -->
          <parameter>
            <parameterName value="@UserId"/>
            <dbType value="String"/>
            <size value="20"/>
            <layout type="log4net.Layout.PatternLayout"/>
          </parameter>
          <!--自定义UserName -->
          <parameter>
            <parameterName value="@UserName"/>
            <dbType value="String"/>
            <size value="50"/>
            <layout type="log4net.Layout.PatternLayout"/>
          </parameter>
          <!--日志信息Message -->
          <parameter>
            <parameterName value="@Message"/>
            <dbType value="String"/>
            <size value="4000"/>
            <layout type="log4net.Layout.PatternLayout"/>
          </parameter>
          <!--异常信息Exception -->
          <parameter>
            <parameterName value="@Exception"/>
            <dbType value="String"/>
            <size value="2000"/>
            <layout type="log4net.Layout.PatternLayout"/>
          </parameter>
        </appender>
        <root>
          <level value="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:PersonLongtengLongtengSlnSendEvaluateDataToProvinceApp.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配置文件如下

    <?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="LogLog.txt"/>
          <param name="AppendToFile" value="true"/>
          <param name="MaxSizeRollBackups" value="100"/>
          <param name="MaximumFileSize" value="2MB"/>
          <param name="RollingStyle" value="Size"/>
          <param name="StaticLogFileName" value="true"/>
          <!--<param name="Encoding" value="utf-8" />-->//注释掉,使用下面的自定义转换SendEvaluateDataToProvinceConsole.MyLayout,下面的同理
          <layout type="log4net.Layout.PatternLayout">
            <param name="ConversionPattern" value="%-5p %d [%c] %m%n"/>
          </layout>
        </appender>
        <!--日志输出到Console-->
        <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
          <mapping>
            <level value="ERROR"/>
            <foreColor value="White"/>
            <backColor value="Red,HighIntensity"/>
          </mapping>
          <mapping>
            <level value="DEBUG"/>
            <backColor value="Green"/>
          </mapping>
          <mapping>
            <level value="Info"/>
            <backColor value="Yellow"/>
          </mapping>
          <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"/>
          </layout>
          <filter type="log4net.Filter.LevelRangeFilter">
            <param name="LevelMin" value="Debug"/>
            <param name="LevelMax" value="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="100" />一百条才插入-->
          <bufferSize value="1"/>
          <!--日志数据库连接串-->
          <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
          <connectionString value="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="System.Data.SQLite.SQLiteConnection, System.Data, Version=1.0.65.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139"/>-->
          <!--<connectionString value="Data source=F:PersonLongtengLongtengSlnSendEvaluateDataToProvinceConsoleDatamysqlite.db;Connect Timeout=15"/>-->
          <!--日志数据库脚本-->
          <commandText value="INSERT INTO LOG([Date],[UserId],[UserName],[Message],[Exception]) VALUES (@Date,@UserId,@UserName,@Message,@Exception)"/>
          <!--日志时间Date -->
          <parameter>
            <parameterName value="@Date"/>
            <dbType value="DateTime"/>
            <layout type="log4net.Layout.RawTimeStampLayout"/>
          </parameter>
          <!--自定义UserId -->
          <parameter>
            <parameterName value="@UserId"/>
            <dbType value="String"/>
            <size value="20"/>
            <!--<layout type="log4net.Layout.PatternLayout"/>-->
            <layout type="SendEvaluateDataToProvinceConsole.MyLayout">
              <conversionPattern value="%Property{UserId}" />
            </layout>
          </parameter>
          <!--自定义UserName -->
          <parameter>
            <parameterName value="@UserName"/>
            <dbType value="String"/>
            <size value="50"/>
            <!--<layout type="log4net.Layout.PatternLayout"/>-->
            <layout type="SendEvaluateDataToProvinceConsole.MyLayout">
              <conversionPattern value="%Property{UserName}" />
            </layout>
          </parameter>
          <!--日志信息Message -->
          <parameter>
            <parameterName value="@Message"/>
            <dbType value="String"/>
            <size value="4000"/>
            <!--<layout type="log4net.Layout.PatternLayout"/>-->
            <layout type="SendEvaluateDataToProvinceConsole.MyLayout">
              <conversionPattern value="%Property{Message}" />
            </layout>
          </parameter>
          <!--异常信息Exception -->
          <parameter>
            <parameterName value="@Exception"/>
            <dbType value="String"/>
            <size value="2000"/>
            <!--<layout type="log4net.Layout.PatternLayout"/>-->
            <!--<layout type="log4net.Layout.ExceptionLayout" />-->
            <layout type="SendEvaluateDataToProvinceConsole.MyLayout">
              <conversionPattern value="%Property{Exception}" />
            </layout>
          </parameter>
        </appender>
        <root>
          <level value="all"/>
          <appender-ref ref="RollingLogFileAppender"/>
          <appender-ref ref="ColoredConsoleAppender"/>
          <appender-ref ref="AdoNetAppender"/>
        </root>
      </log4net>
      <startup>
        <supportedRuntime version="v2.0.50727"/>
      </startup>
    </configuration>

     在运行的话数据库中的运行结果如下:

  • 相关阅读:
    python-文件操作
    python之-字符编码
    课程总结
    IO流文件输出流的应用
    字符串的基本操作
    数据结构字符串实训报告
    窗口的切换
    事件处理
    Java异常处理
    二维数组实现转置
  • 原文地址:https://www.cnblogs.com/1175429393wljblog/p/11983684.html
Copyright © 2020-2023  润新知