Asp.net.WebForm如何使用Log4net记录文件日志

1、首先下载log4net.dll文件(百度云盘有,可下载)

 链接:https://pan.baidu.com/s/1AlftcQGmOlw88eARo8J4Rw 

提取码:zfdf

2、添加到WebForm项目的dll文件夹下

 3、项目引用log4net.dll文件

 4、项目的config文件添加log4net的日志配置

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="log4net" type="System.Configuration.IgnoreSectionHandler"/>
  </configSections>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <log4net>
    <!--定义输出到文件中-->
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <!--定义文件存放位置-->
      <file value="log\\"/>
      <appendToFile value="true"/>
      <rollingStyle value="Date"/>
      <datePattern value="yyyy\\yyyyMM\\yyyyMMdd'.txt'"/>
      <staticLogFileName value="false"/>
      <param name="MaxSizeRollBackups" value="1000"/>
      <layout type="log4net.Layout.PatternLayout">
        <!--输出格式-->
        <conversionPattern value="%newline %n记录时间:%date %n线程ID:[%thread] %n日志级别:%-5level %n出错类:%logger property: [%property{NDC}] - %n错误描述:%message%newline"/>
      </layout>
    </appender>

   <!--定义输出到SQL Server数据库中-->
    <!--  
    在SQL Server中创建表的SQL语句  
    CREATE TABLE [dbo].[Log] (  
    [Id] [int] IDENTITY (1, 1) NOT NULL,  
    [Date] [datetime] NOT NULL,  
    [Thread] [varchar] (255) NOT NULL,  
    [Level] [varchar] (50) NOT NULL,  
    [Logger] [varchar] (255) NOT NULL,  
    [Message] [varchar] (4000) NOT NULL,  
    [Exception] [varchar] (2000) NULL  
);  
    -->

    <appender name="AdoNetAppenderSQLServer" type="log4net.Appender.AdoNetAppender">
      <bufferSize value="1" />
      <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      <connectionString value="Data Source=Sc-201503031243\SQLEXPRESS;Initial Catalog=RoleDemo;Persist Security Info=True;User ID=sa;Password=123;" />
      <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="255" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%thread" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@log_level" />
        <dbType value="String" />
        <size value="50" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%level" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@logger" />
        <dbType value="String" />
        <size value="255" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%logger" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@message" />
        <dbType value="String" />
        <size value="4000" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%message" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@exception" />
        <dbType value="String" />
        <size value="2000" />
        <layout type="log4net.Layout.ExceptionLayout" />
      </parameter>
    </appender>
    <root>
      <level value="ALL" />
      <!--文件形式记录日志-->
     <appender-ref ref="RollingLogFileAppender"/>-->
      <!--SQL Server数据库形式记录日志-->
      <appender-ref ref="AdoNetAppenderSQLServer"/>
    </root>    
  </log4net>
</configuration>

5、添加LogHelper.cs日志辅助类文件

using log4net;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;


//注意下面的语句一定要加上,指定log4net使用.config文件来读取配置信息  
//如果是WinForm(假定程序为MyDemo.exe,则需要一个MyDemo.exe.config文件)  
//如果是WebForm,则从web.config中读取相关信息  
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace WebApplication1
{
    public class LogHelper
    {
        /// <summary>
        /// 调用Log4net写日志,日志等级为 :错误(Error)
        /// </summary>
        /// <param name="logContent">日志内容</param>
        public static void WriteLog(string logContent)
        {
            WriteLog(null, logContent, Log4NetLevel.Error);
        }

        /// <summary>
        /// 调用Log4net写日志
        /// </summary>
        /// <param name="logContent">日志内容</param>
        /// <param name="log4Level">记录日志等级,枚举</param>
        public static void WriteLog(string logContent, Log4NetLevel log4Level)
        {
            WriteLog(null, logContent, log4Level);
        }

        /// <summary>
        /// 调用Log4net写日志
        /// </summary>
        /// <param name="type">类的类型,指定日志中错误的具体类。例如:typeof(Index),Index是类名,如果为空表示不指定类</param>
        /// <param name="logContent">日志内容</param>
        /// <param name="log4Level">记录日志等级,枚举</param>
        public static void WriteLog(Type type, string logContent, Log4NetLevel log4Level)
        {
            ILog log = type == null ? LogManager.GetLogger("") : LogManager.GetLogger(type);
          
            switch (log4Level)
            {
                case Log4NetLevel.Warn:
                    log.Warn(logContent);
                    break;
                case Log4NetLevel.Debug:
                    log.Debug(logContent);
                    break;
                case Log4NetLevel.Info:
                    log.Info(logContent);
                    break;
                case Log4NetLevel.Fatal:
                    log.Fatal(logContent);
                    break;
                case Log4NetLevel.Error:
                    log.Error(logContent);
                    break;
            }
        }

    }

    /// <summary>
    /// log4net 日志等级类型枚举
    /// </summary>
    public enum Log4NetLevel
    {
        [Description("警告信息")]
        Warn = 1,
        [Description("调试信息")]
        Debug = 2,
        [Description("一般信息")]
        Info = 3,
        [Description("严重错误")]
        Fatal = 4,
        [Description("错误日志")]
        Error = 5
    }

}

6、添加一个index.aspx文件编写调用代码

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="WebApplication1.Index" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button Text="写日志" runat="server" ID="BtnWriteLog"   OnClick="BtnWriteLog_Click" />
    </div>
    </form>
</body>
</html>

后台源码

using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{

    public partial class Index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 调用输出日志按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void BtnWriteLog_Click(object sender, EventArgs e)
        {
            //简单写日志
            LogHelper.WriteLog("简单写日志,欢迎使用log4net日志组件!");
            //写Debug日志
            LogHelper.WriteLog("写Debug日志", Log4NetLevel.Debug);
            //带有类型和日志等级的日志,Index 是类名
            LogHelper.WriteLog(typeof(Index), "带有类型和日志等级的日志", Log4NetLevel.Info);

        }
    }
}

7、查看调用后生成结果视图

 

 

 8、源码下载地址

 

 链接:https://pan.baidu.com/s/1WMrjzCmu16YHzXtY9PqOMg 

提取码:c24y

来源网址:

http://ityouzi.com/archives/csharp-log4net-file-db.html

 

posted @ 2021-09-03 14:44  小小邪  阅读(474)  评论(0编辑  收藏  举报