- <configSections>
- <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>(注意这段代码节点在configSections下,如果在sectionGroup下会认不到)
- </configSections>
<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="LogFile.txt" />
<appendToFile value="true" />
<maximumFileSize value="100KB" />
<maxSizeRollBackups value="2" />
<layout type="log4net.Layout.PatternLayout">
<!--<param name="Header" value="◇" />
<param name="Footer" value="◆" />-->
<param name="ConversionPattern" value="记录时间:%date 线程ID:[%thread] 日志级别:文件:所在行%-5level 出错类:%logger property:[%property{NDC}] - 错误描述:%message%newline"/>
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="RollingLogFileAppender" />
</root>
<logger name="WebService">
<level value="ALL" />
</logger>
</log4net>
- <appender name="AdoNetAppender_Oracle" type="log4net.Appender.AdoNetAppender">
- <connectionType value="System.Data.OracleClient.OracleConnection, System.Data.OracleClient" />
- <connectionString value="data source=[mydatabase];User ID=[user];Password=[password]" />
- <commandText value="INSERT INTO Log (Datetime,Thread,Log_Level,Logger,Message) VALUES (:log_date, :thread, :log_level, :logger, :message)" />
- <bufferSize value="128" />
- <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>
- </appender>
- create table log (
- Datetime timestamp(3),
- Thread varchar2(255),
- Log_Level varchar2(255),
- Logger varchar2(255),
- Message varchar2(4000)
- );
在本例中周公采用了将日志记录到SQLite这个单机数据库的方式,并且还将记录记录日志时的文件名和行号,创建SQLite的SQL语句如下:
- CREATE TABLE Log (
- LogId INTEGER PRIMARY KEY,
- Date DATETIME NOT NULL,
- Level VARCHAR(50) NOT NULL,
- Logger VARCHAR(255) NOT NULL,
- Source VARCHAR(255) NOT NULL,
- Message TEXT DEFAULT NULL
- );
增加的< appender>节点配置如下:
- <appender name="AdoNetAppender_SQLite" type="log4net.Appender.AdoNetAppender">
- <bufferSize value="100" />
- <connectionType value="System.Data.SQLite.SQLiteConnection, System.Data.SQLite, Version=1.0.66.0, Culture=neutral" />
- <!--SQLite连接字符串-->
- <connectionString value="Data Source=c:\\log4net.db;Version=3;" />
- <commandText value="INSERT INTO Log (Date, Level, Logger,Source, Message) VALUES (@Date, @Level, @Logger, @Source, @Message)" />
- <parameter>
- <parameterName value="@Date" />
- <dbType value="DateTime" />
- <layout type="log4net.Layout.RawTimeStampLayout" />
- </parameter>
- <parameter>
- <parameterName value="@Level" />
- <dbType value="String" />
- <layout type="log4net.Layout.PatternLayout">
- <conversionPattern value="%level" />
- </layout>
- </parameter>
- <parameter>
- <parameterName value="@Logger" />
- <dbType value="String" />
- <layout type="log4net.Layout.PatternLayout">
- <conversionPattern value="%logger" />
- </layout>
- </parameter>
- <parameter>
- <parameterName value="@Source" />
- <dbType value="String" />
- <layout type="log4net.Layout.PatternLayout">
- <conversionPattern value="%file:%line" />
- </layout>
- </parameter>
- <parameter>
- <parameterName value="@Message" />
- <dbType value="String" />
- <layout type="log4net.Layout.PatternLayout">
- <conversionPattern value="%message" />
- </layout>
- </parameter>
- </appender>
- <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
- <file value="RollingFileAppender_log.txt" />
- <appendToFile value="true" />
- <rollingStyle value="Size" />
- <maxSizeRollBackups value="10" />
- <maximumFileSize value="100KB" />
- <staticLogFileName value="true" />
- <layout type="log4net.Layout.PatternLayout">
- <conversionPattern value="%date [%thread] (%file:%line) %-5level %logger [%property{NDC}] - %message%newline" />
- </layout>
- </appender>
- <appender name="RollingLogFileAppender_DateFormat" type="log4net.Appender.RollingFileAppender">
- <file value="RollingLogFileAppender_DateFormat_log.txt" />
- <appendToFile value="true" />
- <rollingStyle value="Date" />
- <!--<datePattern value="yyyyMMdd-HHmm" />-->
- <datePattern value="yyyyMMdd" />
- <layout type="log4net.Layout.PatternLayout">
- <conversionPattern value="%date [%thread](%file:%line) %-5level %logger [%property{NDC}] - %message%newline" />
- </layout>
- </appender>
- <root>
- <!--文件形式记录日志-->
- <appender-ref ref="LogFileAppender" />
- <!--控制台控制显示日志-->
- <appender-ref ref="ConsoleAppender" />
- <!--Windows事件日志-->
- <!--<appender-ref ref="EventLogAppender" />-->
- <!--SQLite事件日志-->
- <appender-ref ref="AdoNetAppender_SQLite" />
- <!--RollingFileAppender事件日志-->
- <appender-ref ref="RollingFileAppender" />
- <!--RollingFileAppender事件日志,每天一个日志-->
- <appender-ref ref="RollingLogFileAppender_DateFormat" />
- <!-- 如果不启用相应的日志记录,可以通过这种方式注释掉
- <appender-ref ref="AdoNetAppender_Access" />
- -->
- </root>
- using System;
- using System.Collections.Generic;
- using System.Text;
- using log4net;
- using System.Reflection;
- //注意下面的语句一定要加上,指定log4net使用.config文件来读取配置信息
- //如果是WinForm(假定程序为MyDemo.exe,则需要一个MyDemo.exe.config文件)
- //如果是WebForm,则从web.config中读取相关信息
- [assembly: log4net.Config.DOMConfigurator()](这句要加在AssemblyInfo.cs,不然log4net不起作用)
- namespace Log4NetDemo
- {
- class Program
- {
- static void Main(string[] args)
- {
- Random random = new Random();
- for (int i = 0; i < 1; i++)
- {
- //创建日志记录组件实例
- //ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
- ILog log=log4net.LogManager.GetLogger(typeof(Program));
- //记录错误日志
- //log.Error("error", new Exception("在这里发生了一个异常,Error Number:"+random.Next()));
- //记录严重错误
- //log.Fatal("fatal", new Exception("在发生了一个致命错误,Exception Id:"+random.Next()));
- //记录一般信息
- //log.Info("提示:系统正在运行");
- //记录调试信息
- //log.Debug("调试信息:debug");
- //记录警告信息
- //log.Warn("警告:warn");
- }
- Console.WriteLine("日志记录完毕。");
- Console.Read();
- }
- }
- }
- using System;
- using System.Collections.Generic;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using log4net;
- using System.Reflection;
- [assembly: log4net.Config.XmlConfigurator(Watch = true)]
- public partial class _Default : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!Page.IsPostBack)
- {
- Random random = new Random();
- for (int i = 0; i < 1; i++)
- {
- //创建日志记录组件实例
- ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
- //ILog log = log4net.LogManager.GetLogger(typeof(Program));
- //记录错误日志
- //log.Error("error", new Exception("在这里发生了一个异常,Error Number:"+random.Next()));
- //记录严重错误
- //log.Fatal("fatal", new Exception("在发生了一个致命错误,Exception Id:"+random.Next()));
- //记录一般信息
- //log.Info("提示:系统正在运行");
- //记录调试信息
- //log.Debug("调试信息:debug");
- //记录警告信息
- log.Warn("警告:warn");
- Response.Write("日志记录完毕。");
- }
- }
- }
- }
可以看出它们的代码基本没有区别。
下面是一个在WinForm下的config文件的完整配置,该配置文件所使用的代码就是在上面所使用到的代码,使用LogFileAppender、ConsoleAppender、EventLogAppender、AdoNetAppender_SQLite、RollingFileAppender、RollingLogFileAppender_DateFormat方式记录日志都在本地通过测试。
当然,为了简便,通常的做法是把调用方法写在一个通用类里面,然后调用类的方法,如下:
public class LogHelper
{
public static readonly log4net.ILog InfoLog = log4net.LogManager.GetLogger("InfoLog");
public static readonly log4net.ILog ErrorLog = log4net.LogManager.GetLogger("ErrorLog");
public LogHelper()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 写普通信息
/// </summary>
/// <param name="infoMsg"></param>
public static void WriteLog(string infoMsg)
{
//log4net.ILog InfoLog = log4net.LogManager.GetLogger("InfoLog");
string msg = "";
if (InfoLog.IsInfoEnabled)
{
InfoLog.Info(msg + infoMsg);
}
}
/// <summary>
/// 写错误信息
/// </summary>
/// <param name="infoMsg"></param>
/// <param name="e"></param>
public static void WriteLog(string infoMsg, Exception e)
{
string msg = "异常信息:";
if (ErrorLog.IsErrorEnabled)
{
ErrorLog.Error(msg + infoMsg, e);
}
}
}
在需要使用的页面,直接调用,如:LogHelper.WriteLog("--------Start--------");