• ASP.NET Log4net 记录日志


    1.安装方式一(官网下载)

    2.安装方式二(NuGet安装log4net)

    3.使用步骤

    4.自定义属性:UserIP UserName ActionsClick Message

    概述:Log4net是开源记录日志的API,可记录到:数据库、文档、后台命令

    参考博客:地址

    一 安装方式一(官网下载)

    地址:log4net,版本:2.0.8.0

    PS:

     

     二 安装方式二(NuGet安装log4net)

    三 使用步骤

    1)建一个WebApplication1

    2)  引用 log4net.dll

    3) 修改 AssemblyInfo.cs

    增加:[assembly: log4net.Config.XmlConfigurator(Watch = true)]

    4) 新增 Global.asax,增加下面一段代码

    protected void Application_Start(object sender, EventArgs e)
            {
                //应用程序启动时,自动加载配置log4Net    
                XmlConfigurator.Configure();    
            }

    5)新增log4net.config,注意:bufferSize value="1"  每次都插入数据库, 为 10,则满11条才执行插入11条数据到数据库

    <?xml version="1.0" encoding="utf-8"?>
    <log4net debug="false">
      <appender name="ADONetAppender" type="log4net.Appender.ADONetAppender">
        <bufferSize value="1" />
        <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
        <connectionString value="DATABASE=JXBigData;SERVER=.;UID=sa;PWD=123;Connect Timeout=15;" />
        <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)" />
        <parameter>
          <parameterName value="@log_date" />
          <dbType value="DateTime" />
          <layout type="log4net.Layout.RawTimeStampLayout" />
        </parameter>
        <parameter>
          <parameterName value="@thread" />
          <dbType value="String" />
          <size value="100" />
          <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%t" />
          </layout>
        </parameter>
        <parameter>
          <parameterName value="@log_level" />
          <dbType value="String" />
          <size value="200" />
          <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%p" />
          </layout>
        </parameter>
        <parameter>
          <parameterName value="@logger" />
          <dbType value="String" />
          <size value="500" />
          <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%logger" />
          </layout>
        </parameter>
        <parameter>
          <parameterName value="@message" />
          <dbType value="String" />
          <size value="3000" />
          <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%m" />
          </layout>
        </parameter>
        <parameter>
          <parameterName value="@exception" />
          <dbType value="String" />
          <size value="4000" />
          <layout type="log4net.Layout.ExceptionLayout" />
        </parameter>
      </appender>
      <!-- setup the root category, add the appenders and set the default level -->
      <root>
        <level value="WARN"/>
        <level value="INFO"/>
        <level value="DEBUG"/>
        <level value="FINE"/>
        <appender-ref ref="ADONetAppender" />
      </root>
      <!-- specify the level for some specific categories -->
      <logger name="iNotes">
        <level value="WARN"/>
        <level value="INFO"/>
        <level value="DEBUG"/>
        <level value="FINE"/>
        <appender-ref ref="ADONetAppender"/>
      </logger>
      <logger name="StellaLogger">
        <level value="ALL"/>
        <appender-ref ref="AdoNetAppender" />
      </logger>
    </log4net>

    6) 修改Web.Config  ,添加下面代码到节点:configuration

    <configSections>  
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>  
      </configSections>  
       <log4net configSource="log4net.config"/>  

    7)调用方法

    //创建日志记录组件实例
                ILog log = log4net.LogManager.GetLogger(this.GetType());
                //记录错误日志
                log.Error("error", new Exception("发生了一个异常"));
                //记录严重错误
                log.Fatal("fatal", new Exception("发生了一个致命错误"));
                //记录一般信息
                log.Info("info");
                //记录调试信息
                log.Debug("debug");
                //记录警告信息
                log.Warn("warn");     
    public class LogHelper
        {
            /// <summary>
            /// 错误
            /// </summary>
            /// <param name="userIP">IP</param>
            /// <param name="userName">用户</param>
            /// <param name="actionLink">动作事件</param>
            /// <param name="message">错误内容</param>
            public static void Error(string logger, string userIP, string userName, string actionsClick, string message)
            {
                ILog log = log4net.LogManager.GetLogger(logger);
                log.Error(new LogContent(userIP, userName, actionsClick, message));
            }
        }

    8) 新增数据库表:Log

    USE [JXBigData]
    GO
    
    /****** Object:  Table [dbo].[Log]    Script Date: 10/26/2017 17:22:56 ******/
    SET ANSI_NULLS ON
    GO
    
    SET QUOTED_IDENTIFIER ON
    GO
    
    SET ANSI_PADDING ON
    GO
    
    CREATE TABLE [dbo].[Log](
        [ID] [int] IDENTITY(1,1) NOT NULL,
        [Date] [datetime] NOT NULL,
        [Thread] [varchar](255) NOT NULL,
        [Level] [varchar](20) NOT NULL,
        [Logger] [varchar](255) NOT NULL,
        [Message] [varchar](4000) NOT NULL,
        [Exception] [varchar](3000) NULL,
        [UserIP] [varchar](50) NULL,
        [UserName] [nvarchar](100) NULL,
        [ActionsClick] [nvarchar](50) NULL,
     CONSTRAINT [PK_Log] PRIMARY KEY CLUSTERED 
    (
        [ID] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    GO
    
    SET ANSI_PADDING OFF
    GO

    四 自定义属性 

    1)新增下面代码(自定义属性类):Log4NetApply.cs

    using log4net.Layout;
    using log4net.Layout.Pattern;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Log4NetApply
    {
        /// <summary>  
        /// 包含了所有的自定字段属性  
        /// </summary>  
        public class LogContent
        {
            public LogContent(string macAddress, string computerName, string actionsclick, string description)
            {
                UserIP = macAddress;
                UserName = computerName;
                ActionsClick = actionsclick;
                Message = description;
            }
    
            /// <summary>  
            /// 访问IP  
            /// </summary>  
            public string UserIP { get; set; }
    
            /// <summary>  
            /// 系统登陆用户  
            /// </summary>  
            public string UserName { get; set; }
    
            /// <summary>  
            /// 动作事件  
            /// </summary>  
            public string ActionsClick { get; set; }
    
            /// <summary>  
            /// 日志描述信息  
            /// </summary>  
            public string Message { get; set; }
    
    
        }  
        public class MyLayout : PatternLayout
        {
            public MyLayout()
            {
                this.AddConverter("property", typeof(LogInfoPatternConverter));
            }
        }
    
        public class LogInfoPatternConverter : PatternLayoutConverter
        {
    
            protected override void Convert(System.IO.TextWriter writer, log4net.Core.LoggingEvent loggingEvent)
            {
                if (Option != null)
                {
                    // Write the value for the specified key  
                    WriteObject(writer, loggingEvent.Repository, LookupProperty(Option, loggingEvent));
                }
                else
                {
                    // Write all the key value pairs  
                    WriteDictionary(writer, loggingEvent.Repository, loggingEvent.GetProperties());
                }
            }
            /// <summary>  
            /// 通过反射获取传入的日志对象的某个属性的值  
            /// </summary>  
            /// <param name="property"></param>  
            /// <returns></returns>  
    
            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;
            }
        }
    }

    2)修改log4net.config

    <!--自定义Message -->
        <parameter>
          <parameterName value="@message" />
          <dbType value="String" />
          <size value="3000" />
          <layout type="Log4NetApply.MyLayout" >
            <conversionPattern value = "%property{Message}"/>
          </layout>
        </parameter>
        <!--自定义UserName -->
        <parameter>
          <parameterName value="@userName" />
          <dbType value="String" />
          <size value="100" />
          <layout type="Log4NetApply.MyLayout" >
            <conversionPattern value = "%property{UserName}"/>
          </layout>
        </parameter>
        <!--自定义UserIP -->
        <parameter>
          <parameterName value="@userIP" />
          <dbType value="String" />
          <size value="50" />
          <layout type="Log4NetApply.MyLayout" >
            <conversionPattern value = "%property{UserIP}"/>
          </layout>
        </parameter>
        <!--自定义ActionsClick -->
        <parameter>
          <parameterName value="@actionsClick" />
          <dbType value="String" />
          <size value="50" />
          <layout type="Log4NetApply.MyLayout" >
            <conversionPattern value = "%property{ActionsClick}"/>
          </layout>
        </parameter>
    天生我材必有用,千金散尽还复来
  • 相关阅读:
    使用iOS网络请求
    Invalid RNPermission 'ios.permission.xxx'. should be one of: ( )
    React Native 报错 Error: spawn EACCES 权限
    React Native 适配Android物理返回键,实现连续两次点击退出
    图解:平衡二叉树,AVL树
    NOIP 骗分技巧
    P1004 方格取数
    5. 最长回文子串
    全链路压测自动化实践
    深度学习在美团配送ETA预估中的探索与实践
  • 原文地址:https://www.cnblogs.com/ligenyun/p/7735487.html
Copyright © 2020-2023  润新知