通过代码配置 Log4net来实现日志记录

时间:2022-11-01 15:45:18

通过代码来创建配置文件,优点看起来更为简洁,不过还得看需求吧,之前我博客也写了一篇通过读取不同的配置文件还实现配置不同日志类型。

//记录异常日志数据库连接字符串
private const string _ConnectionString = @"Data Source=.;Initial Catalog=Test;User ID=sa;Password=123456";

通过代码配置 Log4net来实现日志记录通过代码配置 Log4net来实现日志记录
使用SQLSERVER记录异常日志 + LoadADONetAppender()

 #region 使用SQLSERVER记录异常日志 + LoadADONetAppender()
/// <summary>
/// 使用SQLSERVER记录异常日志
/// </summary>
/// <Author>Ryanding</Author>
/// <date>2011-05-01</date>
private static void LoadADONetAppender()
{
LoadFileAppender(); log4net.Repository.Hierarchy.Hierarchy hier =
log4net.LogManager.GetLoggerRepository() as log4net.Repository.Hierarchy.Hierarchy; if (hier != null)
{
log4net.Appender.AdoNetAppender adoAppender = new log4net.Appender.AdoNetAppender();
adoAppender.Name = "AdoNetAppender";
adoAppender.CommandType = CommandType.Text;
adoAppender.BufferSize = 1;
adoAppender.ConnectionType = "System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
adoAppender.ConnectionString = _ConnectionString;
adoAppender.CommandText = @"INSERT INTO System__Log_Log4Net ([AddDate],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)";
adoAppender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@log_date", DbType = System.Data.DbType.DateTime, Layout = new log4net.Layout.RawTimeStampLayout() });
adoAppender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@thread", DbType = System.Data.DbType.String, Size = 255, Layout = new Layout2RawLayoutAdapter(new PatternLayout("%thread")) });
adoAppender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@log_level", DbType = System.Data.DbType.String, Size = 50, Layout = new Layout2RawLayoutAdapter(new PatternLayout("%level")) });
adoAppender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@logger", DbType = System.Data.DbType.String, Size = 255, Layout = new Layout2RawLayoutAdapter(new PatternLayout("%logger")) });
adoAppender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@message", DbType = System.Data.DbType.String, Size = 4000, Layout = new Layout2RawLayoutAdapter(new PatternLayout("%message")) });
adoAppender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@exception", DbType = System.Data.DbType.String, Size = 4000, Layout = new Layout2RawLayoutAdapter(new ExceptionLayout()) });
adoAppender.ActivateOptions();
BasicConfigurator.Configure(adoAppender);
} }
#endregion
通过代码配置 Log4net来实现日志记录通过代码配置 Log4net来实现日志记录
使用文本记录异常日志 + LoadFileAppender()#region 使用文本记录异常日志 + LoadFileAppender()
/// <summary>
/// 使用文本记录异常日志
/// </summary>
/// <Author>Ryanding</Author>
/// <date>2011-05-01</date>
private static void LoadFileAppender()
{
string currentPath = AppDomain.CurrentDomain.BaseDirectory;
string txtLogPath = string.Empty;
string iisBinPath = AppDomain.CurrentDomain.RelativeSearchPath; if (!string.IsNullOrEmpty(iisBinPath))
txtLogPath = Path.Combine(iisBinPath, "Log4netFile.txt");
else
txtLogPath = Path.Combine(currentPath, "Log4netFile.txt"); log4net.Repository.Hierarchy.Hierarchy hier =
log4net.LogManager.GetLoggerRepository() as log4net.Repository.Hierarchy.Hierarchy; FileAppender fileAppender = new FileAppender();
fileAppender.Name = "LogFileAppender";
fileAppender.File = txtLogPath;
fileAppender.AppendToFile = true; PatternLayout patternLayout = new PatternLayout();
patternLayout.ConversionPattern = "记录时间:%date 线程ID:[%thread] 日志级别:%-5level 出错类:%logger property:[%property{NDC}] - 错误描述:%message%newline";
patternLayout.ActivateOptions();
fileAppender.Layout = patternLayout; //选择UTF8编码,确保中文不乱码。
fileAppender.Encoding = Encoding.UTF8; fileAppender.ActivateOptions();
BasicConfigurator.Configure(fileAppender); }
#endregion
通过代码配置 Log4net来实现日志记录通过代码配置 Log4net来实现日志记录
使用日志记录方法protected void Page_Load(object sender, EventArgs e)
{
使用文本记录异常日志 + LoadFileAppender();
使用文本记录异常日志 + LoadFileAppender(); }
通过代码配置 Log4net来实现日志记录通过代码配置 Log4net来实现日志记录
数据库执行脚本SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Log]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Log](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Date] [datetime] NOT NULL,
[Thread] [varchar](255) NULL,
[Level] [varchar](50) NULL,
[Logger] [varchar](255) NULL,
[Message] [varchar](4000) NULL,
[Exception] [varchar](4000) NULL,
PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
Go