一、环境说明:
开发工具:vs2010 ,数据库:oracle 11g ,版本:log4net的目前最新版本1.2.13.0 ; Oracle.ManagedDataAccess.dll Version 4.121.1.0
二、官网dll准备
log4net http://mirrors.hust.edu.cn/apache//logging/log4net/binaries/log4net-1.2.13-bin-newkey.zip
Oracle.ManagedDataAccess.dll 官网 http://www.oracle.com/technetwork/topics/dotnet/downloads/index.html
三、实现步骤(以个人建立的项目为例子解说)
1、建立项目log4netTest5,把dll放在Lib文件内, 打开项目 引用 把dll 引入项目
2、建立log4net.config 配置文件(周公等网上的达人都详解的很清楚了,我就讲解oracle哪一部分)
注意: <appender name="AdoNetAppender_ORCL" type="log4net.Appender.OracleAppender">
数据驱动
<connectionType value="Oracle.ManagedDataAccess.Client.OracleConnection,Oracle.ManagedDataAccess, Version=4.121.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342" /> 数据库连接串
<connectionString value="Data Source=//localhost:1521/orcl;User ID=user;Password=user;" />
还有
<commandText value="insert into SECURITY_LOG4NET
按照自己的实际情况自己修改
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections> <log4net> <appender name="AdoNetAppender_ORCL" type="log4net.Appender.OracleAppender">
<bufferSize value="1"/>
<connectionType value="Oracle.ManagedDataAccess.Client.OracleConnection,Oracle.ManagedDataAccess, Version=4.121.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
<connectionString value="Data Source=//localhost:1521/orcl;User ID=user;Password=user;" />
<commandText value="insert into SECURITY_LOG4NET (LOG_DATE,LOG_LEVEL,LOG_MESSAGE,LOG_EXCEPTION,LOG_LOGGER,LOG_SOURCE,USERID,LOGTYPE) VALUES (:log_date, :log_level,:log_message, :log_exception, :logger, :source,:USERID,:LOGTYPE)"/>
<parameter>
<parameterName value=":log_date" />
<dbType value="DateTime" />
<layout type="log4net.Layout.RawTimeStampLayout">
<conversionPattern value="%d{yyyy/MM/dd HH:mm:ss}" />
</layout>
</parameter>
<parameter>
<parameterName value=":log_level" />
<dbType value="String" />
<size value="10" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level" />
</layout>
</parameter>
<parameter>
<parameterName value=":log_message" />
<dbType value="String" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%m" />
</layout>
</parameter>
<parameter>
<parameterName value=":log_exception" />
<dbType value="String" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%exception" />
</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=":source" />
<dbType value="String" />
<size value="1000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%file:%line" />
</layout>
</parameter>
<parameter>
<parameterName value=":USERID" />
<dbType value="String" />
<size value="100" />
<layout type="Log4NetToDatabase.CustomLayout">
<conversionPattern value="%USERID" />
</layout>
</parameter>
<parameter>
<parameterName value=":LOGTYPE" />
<dbType value="String" />
<size value="100" />
<layout type="Log4NetToDatabase.CustomLayout">
<conversionPattern value="%LOGTYPE" />
</layout>
</parameter>
</appender> <root>
<level value ="ALL"/>
<appender-ref ref="AdoNetAppender_ORCL"/>
</root> </log4net>
</configuration>
3、自己实现 OracleAppender.cs 和OracleAppenderParameter.cs
(我直接取自http://www.cnblogs.com/hnsongbiao/p/4216147.html#commentform)
public class OracleAppender : BufferingAppenderSkeleton
{
// Fields
private static readonly Type declaringType = typeof(AdoNetAppender);
private string m_commandText;
private CommandType m_commandType = CommandType.Text;
private string m_connectionString;
private string m_connectionType;
private OracleCommand m_dbCommand;
private OracleConnection m_dbConnection;
protected ArrayList m_parameters = new ArrayList();
private bool m_reconnectOnError = false;
private SecurityContext m_securityContext;
protected bool m_usePreparedCommand;
private bool m_useTransactions = true; // Methods
public override void ActivateOptions()
{
base.ActivateOptions();
this.m_usePreparedCommand = (this.m_commandText != null) && (this.m_commandText.Length > );
if (this.m_securityContext == null)
{
this.m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this);
}
this.InitializeDatabaseConnection();
this.InitializeDatabaseCommand();
} public void AddParameter(OracleAppenderParameter parameter)
{
this.m_parameters.Add(parameter);
} protected virtual string GetLogStatement(LoggingEvent logEvent)
{
if (this.Layout == null)
{
this.ErrorHandler.Error("ADOAppender: No Layout specified.");
return "";
}
StringWriter writer = new StringWriter(CultureInfo.InvariantCulture);
this.Layout.Format(writer, logEvent);
return writer.ToString();
} private void InitializeDatabaseCommand()
{
if ((this.m_dbConnection != null) && this.m_usePreparedCommand)
{
try
{
this.m_dbCommand = this.m_dbConnection.CreateCommand();
this.m_dbCommand.CommandText = this.m_commandText;
this.m_dbCommand.CommandType = this.m_commandType;
}
catch (Exception exception)
{
this.ErrorHandler.Error("Could not create database command [" + this.m_commandText + "]", exception);
if (this.m_dbCommand != null)
{
try
{
this.m_dbCommand.Dispose();
}
catch
{
}
this.m_dbCommand = null;
}
}
if (this.m_dbCommand != null)
{
try
{
foreach (OracleAppenderParameter parameter in this.m_parameters)
{
try
{
parameter.Prepare(this.m_dbCommand);
}
catch (Exception exception2)
{
this.ErrorHandler.Error("Could not add database command parameter [" + parameter.ParameterName + "]", exception2);
throw;
}
}
}
catch
{
try
{
this.m_dbCommand.Dispose();
}
catch
{
}
this.m_dbCommand = null;
}
}
if (this.m_dbCommand != null)
{
try
{
this.m_dbCommand.Prepare();
}
catch (Exception exception3)
{
this.ErrorHandler.Error("Could not prepare database command [" + this.m_commandText + "]", exception3);
try
{
this.m_dbCommand.Dispose();
}
catch
{
}
this.m_dbCommand = null;
}
}
}
} private void InitializeDatabaseConnection()
{
try
{
this.m_dbConnection = new OracleConnection();
this.m_dbConnection.ConnectionString = this.m_connectionString;
using (this.SecurityContext.Impersonate(this))
{
this.m_dbConnection.Open();
}
}
catch (Exception exception)
{
this.ErrorHandler.Error("Could not open database connection [" + this.m_connectionString + "]", exception);
this.m_dbConnection = null;
}
} protected override void OnClose()
{
base.OnClose();
if (this.m_dbCommand != null)
{
this.m_dbCommand.Dispose();
this.m_dbCommand = null;
}
if (this.m_dbConnection != null)
{
this.m_dbConnection.Close();
this.m_dbConnection = null;
}
} protected virtual Type ResolveConnectionType()
{
Type type;
try
{
type = SystemInfo.GetTypeFromString(this.m_connectionType, true, false);
}
catch (Exception exception)
{
this.ErrorHandler.Error("Failed to load connection type [" + this.m_connectionType + "]", exception);
throw;
}
return type;
} protected override void SendBuffer(LoggingEvent[] events)
{
if (this.m_reconnectOnError && ((this.m_dbConnection == null) || (this.m_dbConnection.State != ConnectionState.Open)))
{
LogLog.Debug(declaringType, "OracleAppender: Attempting to reconnect to database. Current Connection State: " + ((this.m_dbConnection == null) ? "<null>" : this.m_dbConnection.State.ToString()));
this.InitializeDatabaseConnection();
this.InitializeDatabaseCommand();
}
if ((this.m_dbConnection != null) && (this.m_dbConnection.State == ConnectionState.Open))
{
if (this.m_useTransactions)
{
OracleTransaction dbTran = null;
try
{
dbTran = this.m_dbConnection.BeginTransaction();
this.SendBuffer(dbTran, events);
dbTran.Commit();
}
catch (Exception exception)
{
if (dbTran != null)
{
try
{
dbTran.Rollback();
}
catch (Exception)
{
}
}
this.ErrorHandler.Error("Exception while writing to database", exception);
}
}
else
{
this.SendBuffer(null, events);
}
}
} protected virtual void SendBuffer(OracleTransaction dbTran, LoggingEvent[] events)
{
if (!this.m_usePreparedCommand)
{
throw new NotImplementedException();
}
if (this.m_dbCommand != null)
{
ArrayList list = null;
foreach (OracleAppenderParameter parameter in this.m_parameters)
{
list = new ArrayList();
OracleParameter parameter2 = this.m_dbCommand.Parameters[parameter.ParameterName];
foreach (LoggingEvent event2 in events)
{
object obj2 = parameter.Layout.Format(event2);
if (obj2.ToString() == "(null)")
{
obj2 = DBNull.Value;
}
list.Add(obj2);
}
parameter2.Value = list.ToArray();
}
this.m_dbCommand.ArrayBindCount = events.Length;
this.m_dbCommand.ExecuteNonQuery();
}
} // Properties
public string CommandText
{
get
{
return this.m_commandText;
}
set
{
this.m_commandText = value;
}
} public CommandType CommandType
{
get
{
return this.m_commandType;
}
set
{
this.m_commandType = value;
}
} protected OracleConnection Connection
{
get
{
return this.m_dbConnection;
}
set
{
this.m_dbConnection = value;
}
} public string ConnectionString
{
get
{
return this.m_connectionString;
}
set
{
this.m_connectionString = value;
}
} public bool ReconnectOnError
{
get
{
return this.m_reconnectOnError;
}
set
{
this.m_reconnectOnError = value;
}
} public SecurityContext SecurityContext
{
get
{
return this.m_securityContext;
}
set
{
this.m_securityContext = value;
}
} public bool UseTransactions
{
get
{
return this.m_useTransactions;
}
set
{
this.m_useTransactions = value;
}
}
}
public class OracleAppenderParameter
{
// Fields
private DbType m_dbType;
private bool m_inferType = true;
private IRawLayout m_layout;
private string m_parameterName;
private byte m_precision = ;
private byte m_scale = ;
private int m_size = ; // Methods
public virtual void FormatValue(OracleCommand command, LoggingEvent loggingEvent)
{
OracleParameter parameter = command.Parameters[this.m_parameterName];
parameter.Value = this.Layout.Format(loggingEvent);
} public virtual void Prepare(OracleCommand command)
{
OracleParameter param = command.CreateParameter();
param.ParameterName = this.m_parameterName;
if (!this.m_inferType)
{
param.DbType = this.m_dbType;
}
if (this.m_precision != )
{
param.Precision = this.m_precision;
}
if (this.m_scale != )
{
param.Scale = this.m_scale;
}
if (this.m_size != )
{
param.Size = this.m_size;
}
command.Parameters.Add(param);
} // Properties
public DbType DbType
{
get
{
return this.m_dbType;
}
set
{
this.m_dbType = value;
this.m_inferType = false;
}
} public IRawLayout Layout
{
get
{
return this.m_layout;
}
set
{
this.m_layout = value;
}
} public string ParameterName
{
get
{
return this.m_parameterName;
}
set
{
this.m_parameterName = value;
}
} public byte Precision
{
get
{
return this.m_precision;
}
set
{
this.m_precision = value;
}
} public byte Scale
{
get
{
return this.m_scale;
}
set
{
this.m_scale = value;
}
} public int Size
{
get
{
return this.m_size;
}
set
{
this.m_size = value;
}
}
}
4、实现CustomLayout.cs
ReflectionPatternConverter.cs文件
我浏览 誉满中华 博主的文章时,就想拿来就用呀,可惜博主太忙了 留言没有回复, 而且又急用用就自己下载了源码 参照源码和http://blog.****.net/kkkkkxiaofei/article/details/12946913 自己实现了一下,如有问题请留言指出
自定义字段时 一定要 先在 ReflectionPatternConverter.cs 中把自定义字段 映射好
然后 CustomLayout.cs 中
s_globalRulesRegistry = new Hashtable(2);
s_globalRulesRegistry.Add("USERID", typeof(USERIDPatternConverter));
s_globalRulesRegistry.Add("LOGTYPE", typeof(LOGTYPEPatternConverter));
绑定,有多少个自定义字段 就要在这两个cs中对应设置好,layout type 也要指定对地址
5、配置
Global.asax中 Application_Start里添加
log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(Server.MapPath("~") + "\\log4net.config"));
AssemblyInfo.cs 中 添加
[assembly: log4net.Config.XmlConfigurator(ConfigFile = @"log4net.config", Watch = true)]
6、测试一下
简单写个log。cs
private static ILog logOracle = log4net.LogManager.GetLogger("LogOracle");
public static void OracleInfo(Model.SECURITY_LOG4NET logMessage)
{
logOracle.Info(logMessage);
}
//测试写入
Model.SECURITY_LOG4NET model = new Model.SECURITY_LOG4NET();
model.USERID = System.Guid.NewGuid().ToString();
model.LOGTYPE = "Oracle.ManagedDataAccess.Client";
log.OracleInfo(model);
成功写入!
源码给大家做个参考: http://pan.baidu.com/s/1nUFvS 提取码 t45u
本文参考文章:
1、 http://www.cnblogs.com/lightnear/archive/2013/06/04/3117340.html 没有实现自定义 用 Oracle.DataAccess 驱动的
2、http://www.cnblogs.com/hnsongbiao/p/4216147.html#commentform
3、http://*.com/questions/29614827/log4net-appender-adonetappender-connectiontype-oracle-manageddataaccess-client
4、http://blog.****.net/kkkkkxiaofei/article/details/12946913
5、http://zhoufoxcn.blog.51cto.com/792419/429988/