一、数据库日志表结构
- CREATE TABLE [dbo].[WebLog_Msg](
- [LogID] [int] IDENTITY(1,1) NOT NULL,
- [Date] [datetime] NOT NULL,
- [Thread] [nvarchar](255) NULL,
- [Level] [nvarchar](50) NULL,
- [Logger] [nvarchar](255) NULL,
- [Message] [nvarchar](2000) NULL,
- [Exception] [nvarchar](4000) NULL,
- CONSTRAINT [PK_WebLog_Msg] PRIMARY KEY CLUSTERED
- (
- [LogID] ASC
- ))
二、测试类库LoggHelper
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using log4net;
- namespace LogHelper
- {
- public class LoggHelper
- {
- //static LoggHelper()
- //{
- // log4net.Config.XmlConfigurator.Configure();
- //}
- private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(LoggHelper));
- public static void LogInfo()
- {
- log.Info("log日志getretertretrree");
- }
- public static void LogWarn()
- {
- log.Warn("log警告WARNaaaaaaaaaad;");
- }
- public static void LogFatal()
- {
- log.Fatal("log警告WARNaaaaaaaaaad;");
- }
- public static void LogError()
- {
- log.Error("log错误sfsfsfsdfafasdfdsfadffafdsaffasf><><>2eewewjklsfaaaaaaaaaaaaaaaaaaaaaaaaaaaaad;");
- }
- }
- }
三、控制台测试项目
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using LogHelper;
- namespace TestLog4Net
- {
- class Program
- {
- static void Main(string[] args)
- {
- log4net.Config.XmlConfigurator.Configure();
- try
- {
- LoggHelper.LogInfo();
- LoggHelper.LogWarn();
- LoggHelper.LogError();
- LoggHelper.LogFatal();
- Console.ReadLine();
- }
- catch (Exception ex)
- {
- Console.Write(ex);
- }
- }
- }
- }
配置文件内容如下:
- <?xml version="1.0"?>
- <configuration>
- <!--Log4Net config section-->
- <configSections>
- <!--<sectionGroup name="common">
- <section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
- </sectionGroup>-->
- <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
- </configSections>
- <!--<common>
- <logging>
- <factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4Net">
- <arg key="configType" value="INLINE"/>
- </factoryAdapter>
- </logging>
- </common>-->
- <log4net>
- <root>
- <!--OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL-->
- <level value="ALL"/>
- <appender-ref ref="AdoNetAppender_SqlServer"/>
- <appender-ref ref="RollingLogFileAppender"/>
- </root>
- <!--<logger name="ErrorInfo">
- <level value="ALL" />
- <appender-ref ref="RollingLogFileAppender" />
- </logger>-->
- <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
- <filter type="log4net.Filter.LevelRangeFilter">
- <levelMin value="Debug" />
- <levelMax value="Info" />
- </filter>
- <param name="File" value="logerrorInfo.txt"/>
- <param name="AppendToFile" value="true"/>
- <param name="MaxSizeRollBackups" value="10"/>
- <param name="MaximumFileSize" value="2MB"/>
- <param name="RollingStyle" value="Size"/>
- <param name="StaticLogFileName" value="true"/>
- <layout type="log4net.Layout.PatternLayout">
- <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n"/>
- </layout>
- </appender>
- <appender name="AdoNetAppender_SqlServer" type="log4net.Appender.AdoNetAppender">
- <filter type="log4net.Filter.LevelRangeFilter">
- <levelMin value="Warn" />
- <levelMax value="Fatal" />
- </filter>
- <bufferSize value="0" />
- <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
- <connectionString value="server=XXXXX;database=WebLog;user id=UID;password=PSW;Connect Timeout=15;"/>
- <commandText value="INSERT INTO WebLog_Msg([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="2000" />
- <layout type="log4net.Layout.PatternLayout">
- <conversionPattern value="%message" />
- </layout>
- </parameter>
- <parameter>
- <parameterName value="@exception" />
- <dbType value="String" />
- <size value="4000" />
- <layout type="log4net.Layout.ExceptionLayout" />
- </parameter>
- </appender>
- </log4net>
- <!--Log4Net config section end-->
- </configuration>
四、运行结果
1、文件
- 2011-12-31 14:40:17,440 [10] INFO LogHelper.LoggHelper [(null)] - log日志getretertretrree
2、数据库
五、优化log4net在项目中的配置
关注封装日志操作的类库LogHelper:
在AssemblyInfo.cs文件中加入[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Configuration/Log4Net.config", Watch = true)],即加入log4net配置项。
在文件Log4Net.config中配置如下:
- <?xml version="1.0" encoding="utf-8" ?>
- <configuration>
- <!--Log4Net config section-->
- <configSections>
- <!--<sectionGroup name="common">
- <section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
- </sectionGroup>-->
- <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
- </configSections>
- <!--<common>
- <logging>
- <factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4Net">
- <arg key="configType" value="INLINE"/>
- </factoryAdapter>
- </logging>
- </common>-->
- <log4net>
- <root>
- <!--OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL-->
- <level value="ALL"/>
- <appender-ref ref="AdoNetAppender_SqlServer"/>
- <appender-ref ref="RollingLogFileAppender"/>
- </root>
- <!--<logger name="ErrorInfo">
- <level value="ALL" />
- <appender-ref ref="RollingLogFileAppender" />
- </logger>-->
- <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
- <param name="File" value="logerrorInfo.txt"/>
- <param name="AppendToFile" value="true"/>
- <param name="MaxSizeRollBackups" value="10"/>
- <param name="MaximumFileSize" value="2MB"/>
- <param name="RollingStyle" value="Size"/>
- <param name="StaticLogFileName" value="true"/>
- <layout type="log4net.Layout.PatternLayout">
- <!--"%d %t %p %l %m %n”:
- 1、%d输出日志时间点的日期或时间,默认格式为ISO8601,也可以在其后指定格式,比如:%d{yyyy-MM-dd HH:mm:ss},输出类似:2005-7-19 17:49:27,刚好适合插入SQLServer;
- 2、%t 产生该日志事件的线程名;
- 3、%p 日志的log_level,如DEBUG、WARN或者INFO;
- 4、%c 输出所属的类目,通常就是所在类的全名,如“iNotes.Default”;
- 5、%m 日志的内容;
- 6、%l 输出日志事件的发生位置,包括类目名、发生的线程,以及在代码中的行数。如write2database.main(write2database.java:33);
- 7、%n 输出一个回车换行符,Windows平台为“ ”,Unix平台为“ ”
- -->
- <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n"/>
- </layout>
- </appender>
- <appender name="AdoNetAppender_SqlServer" type="log4net.Appender.AdoNetAppender">
- <filter type="log4net.Filter.LevelRangeFilter">
- <levelMin value="Warn" />
- <levelMax value="Fatal" />
- </filter>
- <bufferSize value="0" />
- <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
- <connectionString value="server=XXXX;database=Weblog;user id=UID;password=PSW"/>
- <commandText value="INSERT INTO WebLog_Msg([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="255" />
- <layout type="log4net.Layout.PatternLayout">
- <conversionPattern value="%message" />
- </layout>
- </parameter>
- <parameter>
- <parameterName value="@exception" />
- <dbType value="String" />
- <size value="4000" />
- <layout type="log4net.Layout.ExceptionLayout" />
- </parameter>
- </appender>
- </log4net>
- <!--Log4Net config section end-->
- </configuration>
即把应用程序config文件下有关log4net的所有配置项移除放到单一文件Log4Net.config中,这样给应用程序的配置文件“瘦身”不少,呵呵!
ok,编译类库LoggHelper(可在里面封装对log4net的所有操作),将控制台程序改为
- static void Main(string[] args)
- {
- //log4net.Config.XmlConfigurator.Configure(); //注释掉
- try
- {
- LoggHelper.LogInfo();
- LoggHelper.LogWarn();
- LoggHelper.LogError();
- LoggHelper.LogFatal();
- Console.ReadLine();
- }
- catch (Exception ex)
- {
- Console.Write(ex);
- }
- }
运行,一切ok!
附有关log4net的对数据库写日志的配置:
http://logging.apache.org/log4net/release/config-examples.html