log4net 普通文件、数据库日志

1. 右键项目使用 NuGet 安装 log4net

2. 新建 log4net.config 文件

1. Error 日志
2. Info 日志
3. 自定义日志
4. 数据库日志(含自定义字段

注意:

log4net.config 根目录:

log4net 普通文件、数据库日志

log4net 普通文件、数据库日志

2-1 Error 日志

<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <file value="log\\LogError\\" />
    <appendToFile value="true" />
    <rollingStyle value="Date" />
    <datePattern value="yyyyMMdd'.txt'" />
    <staticLogFileName value="false" />
    <param name="MaxSizeRollBackups" value="100" />
    <layout type="log4net.Layout.PatternLayout">
      <!--每条日志末尾的文字说明-->
      <!--输出格式-->
      <!--样例:2008-03-26 13:42:32,111 [10] INFO  Log4NetDemo.MainClass [(null)] - info-->
      <conversionPattern value="%newline %n记录时间:%date %n线程ID:[%thread] %n日志级别:  %-5level %n错误描述:%message%newline %n" />
    </layout>
  </appender>

  <logger name="logerror">
    <level value="ERROR" />
    <appender-ref ref="RollingLogFileAppender" />
  </logger>

2-2 Info 日志

<appender name="InfoAppender" type="log4net.Appender.RollingFileAppender">
    <file value="Log\\LogInfo\\" />
    <appendToFile value="true" />
    <maxFileSize value="10240" />
    <maxSizeRollBackups value="100" />
    <staticLogFileName value="false" />
    <datePattern value="yyyyMMdd'.txt'" />
    <rollingStyle value="Date" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%newline %n记录时间:%date %n线程ID:[%thread] %n日志级别:  %-5level %n日志描述:%message%newline %n" />
    </layout>
  </appender>

  <logger name="loginfo">
    <level value="INFO" />
    <appender-ref ref="InfoAppender" />
  </logger>

2-3 自定义日志

<appender name="MonitorAppender" type="log4net.Appender.RollingFileAppender">
    <file value="Log\\LogMonitor\\" />
    <appendToFile value="true" />
    <maxFileSize value="10240" />
    <maxSizeRollBackups value="100" />
    <staticLogFileName value="false" />
    <datePattern value="yyyyMMdd'.txt'" />
    <rollingStyle value="Date" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%newline %n记录时间:%date %n线程ID:[%thread] %n日志级别:  %-5level %n跟踪描述:%message%newline %n" />
    </layout>
  </appender>

  <logger name="logmonitor">
    <level value="Monitor" />
    <appender-ref ref="MonitorAppender" />
  </logger>

2-4 数据库日志

建议先将 官方数据库日志示例 跑通后,再加入自定义字段。

SqlServer :

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,
    [job_code] [varchar] (100) NULL,
    [stream_id] [varchar] (100) NULL
)

配置说明:
log4net 普通文件、数据库日志

自定义类:

using log4net.Layout;
using log4net.Layout.Pattern;
using System;
using System.Collections.Generic;
using System.Linq;
using log4net.Core;
using System.IO;
using System.Reflection;

namespace RaysCloud.Common
{
    /// <summary>
    /// 自定义日志类  对应数据库表字段
    /// </summary>
    public class LogContent
    {
        public string job_code { get; set; }
        public string stream_id { get; set; }
    }

    public class CustomLoyout : PatternLayout
    {
        public CustomLoyout()
        {
            this.AddConverter("property", typeof(LogInfoPatternConverter));
        }
    }

    public class LogInfoPatternConverter : 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());
            }
        }

        /// <summary>
        /// 反射获取传入日志对象的某个属性的值
        /// </summary>
        /// <param name="property"></param>
        /// <param name="loggingEvent"></param>
        /// <returns></returns>
        private object LookupProperty(string property, LoggingEvent loggingEvent)
        {
            object propertyValue = string.Empty;
            PropertyInfo propertyInfo = loggingEvent.MessageObject.GetType().GetProperty(property);

            if (property != null)
            {
                propertyValue = propertyInfo.GetValue(loggingEvent.MessageObject, null);
            }
            return propertyValue;
        }
    }
}

log4net 配置:

<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
    <bufferSize value="100" />
    <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    <connectionString value="data source=[database server];initial catalog=[database name];integrated security=false;persist security info=True;User ID=[user];Password=[password]" />
    <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>
    
    <logger name="logadonet">
        <level value="ALL"/>
    <appender-ref ref="AdoNetAppender"/>
  </logger>
</appender>

3.Web.config 配置

log4net 普通文件、数据库日志

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

4.Global.aspx

protected void Application_Start()
 {
     log4net.Config.XmlConfigurator.Configure();    // log4net 配置
 }

5.LogHelper.cs

随便写的一个辅助类,可自行扩展

using System;

namespace RaysCloud.Common
{
    /// <summary>
    /// 日志类
    /// </summary>
    public class LogHelper
    {
        private static readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("loginfo");
        private static readonly log4net.ILog logerror = log4net.LogManager.GetLogger("logerror");
        private static readonly log4net.ILog logmonitor = log4net.LogManager.GetLogger("logmonitor");
        private static readonly log4net.ILog log_db = log4net.LogManager.GetLogger("logadonet");

        /// <summary>
        /// 错误日志
        /// </summary>
        /// <param name="errorMsg">错误信息</param>
        /// <param name="ex">异常</param>
        public static void Error(string errorMsg, Exception ex = null)
        {
            logerror.Error(errorMsg, ex);
        }
        /// <summary>
        /// 普通日志
        /// </summary>
        /// <param name="msg">信息</param>
        public static void Info(string msg)
        {
            loginfo.Info(msg);
        }

        /// <summary>
        /// 监控日志
        /// </summary>
        /// <param name="msg">信息</param>
        public static void Monitor(string msg)
        {
            logmonitor.Info(msg);
        }

        #region 写入日志到数据库  http://blog.csdn.net/kongwei521/article/details/52242319
        public static void ErrorToDB(object message, Exception ex = null)
        {
            log_db.Error(message, ex);
        }

        public static void InfoToDB(object message, Exception ex = null)
        {
            log_db.Info(message, ex);
        }
        #endregion

    }
}

6.日志截图:

log4net 普通文件、数据库日志

log4net 普通文件、数据库日志

源码:https://git.oschina.net/PoloN...

本文数据库日志参考于:http://blog.csdn.net/kongwei5...