好记性不如烂笔头。

ASP.NET中使用Log4Net(输出到sql数据库)

创建log表

USE [dbname]
GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Log_Date]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Log] DROP CONSTRAINT [DF_Log_Date]
END

GO

USE [dbname]
GO

/****** Object:  Table [dbo].[Log]    Script Date: 01/07/2015 13:24:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Log]') AND type in (N'U'))
DROP TABLE [dbo].[Log]
GO

USE [dbname]
GO

/****** Object:  Table [dbo].[Log]    Script Date: 01/07/2015 13:24:09 ******/
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] NULL,
    [Thread] [varchar](255) NULL,
    [Level] [varchar](50) NULL,
    [Logger] [varchar](255) NULL,
    [Message] [varchar](max) NULL,
    [Exception] [varchar](max) NULL,
    [userLog] [varchar](max) NULL,
    [userName] [varchar](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

ALTER TABLE [dbo].[Log] ADD  CONSTRAINT [DF_Log_Date]  DEFAULT (getdate()) FOR [Date]
GO

自定义字段反射

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net.Layout;
using log4net.Layout.Pattern;
using System.Reflection;

/// <summary>
///log4net 反射类
/// </summary>
/// 
public class LogLayout : PatternLayout
{
    public LogLayout()
    {
        this.AddConverter(("property"), typeof(LogMsgPatternConver));
    }
}


public class LogMsgPatternConver : PatternLayoutConverter
{
    protected override void Convert(System.IO.TextWriter writer, log4net.Core.LoggingEvent loggingEvent)
    {
        if (Option != null)
        {
            WriteObject(writer, loggingEvent.Repository, LookupProperty(Option, loggingEvent));
        }
        else
        {
            WriteDictionary(writer, loggingEvent.Repository, loggingEvent.GetProperties());
        }
    }

    protected object LookupProperty(string property, log4net.Core.LoggingEvent loggingEvent)
    {
        object propertyValue = string.Empty;
        PropertyInfo pi = loggingEvent.MessageObject.GetType().GetProperty(property);
        if (null != pi)
            propertyValue = pi.GetValue(loggingEvent.MessageObject, null);
        return propertyValue;
    }
}

Web.Config配置

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

 

log4net.config 配置文件

<?xml version="1.0"?>
<log4net>
    <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
        <bufferSize value="1" />
        <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=2.0.0.0, Culture=neutral,PublicKeyToken=b77a5c561934e089"/>
        <connectionString value="Data Source=.;Initial Catalog=DBNAME;User ID=sa;Password=sa" />
        <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception],[userlog],[username]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception,@userlog,@username)" />
        <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" value="%thread">
            </layout>
        </parameter>
        <parameter>
            <parameterName value="@log_level" />
            <dbType value="String" />
            <size value="50" />
            <layout type="log4net.Layout.PatternLayout" value="%level">
            </layout>
        </parameter>
        <parameter>
            <parameterName value="@logger" />
            <dbType value="String" />
            <size value="255" />
            <layout type="log4net.Layout.PatternLayout" value="%class.%method">
            </layout>
        </parameter>
        <parameter>
            <parameterName value="@message" />
            <dbType value="String" />
            <size value="4000" />
            <layout type="log4net.Layout.PatternLayout" value="%message">
            </layout>
        </parameter>
        <parameter>
            <parameterName value="@exception" />
            <dbType value="String" />
            <size value="2000" />
            <layout type="log4net.Layout.ExceptionLayout" />
        </parameter>
        <parameter>
            <parameterName value="@userlog" />
            <dbType value="String" />
            <size value="2000" />
            <layout type="LogLayout" >
                <param name="ConversionPattern" value="%property{UserLog}" />
            </layout>
        </parameter>
        <parameter>
            <parameterName value="@username" />
            <dbType value="String" />
            <size value="2000" />
            <layout type="LogLayout" >
                <param name="ConversionPattern" value="%property{UserName}" />

            </layout>
        </parameter>
    </appender>

    <root>
        <level value="ALL" />
        <appender-ref ref="AdoNetAppender" />
        <appender-ref ref="LogFileAppender" />
        <appender-ref ref="HttpTraceAppender" />
        <appender-ref ref="EventLogAppender" />
        <appender-ref ref="RollingLogFileAppender" />
    </root>

</log4net>

Global.asax 加载配置

void Application_Start(object sender, EventArgs e)
{
      log4net.Config.XmlConfigurator.Configure();
}