Log4net 自定义字段 写入Oracle 使用ODP.NET Managed驱动

时间:2022-09-23 22:24:27

一、环境说明:

开发工具: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.csdn.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.csdn.net/kkkkkxiaofei/article/details/12946913

5、http://zhoufoxcn.blog.51cto.com/792419/429988/

Log4net 自定义字段 写入Oracle 使用ODP.NET Managed驱动的更多相关文章

  1. log4net自定义字段写入SqlServer数据库 ASP&period;net

    首先申明,本示例经过本作者亲自试验通过,可以运行 第一步 编写log4net配置文件 此处为Log.xml,该文件放在与Web.config平级的位置 <?xml version="1 ...

  2. NLog 自定义字段 写入 oracle

    1.通过Nuget安装NLog 下载,简单入门 请参照 我刚才转的几篇文章,下面我直接贴代码 2.建表语句 create table TBL_LOG ( id ) not null, appname ...

  3. &lbrack;转&rsqb;NLog 自定义字段 写入 oracle

    本文转自:http://www.cnblogs.com/skyapplezhao/p/5690695.html 1.通过Nuget安装NLog 下载,简单入门 请参照 我刚才转的几篇文章,下面我直接贴 ...

  4. Log4net 自定义字段到数据库

    今天要求做个log4net自定义字段到数据库,在网上找了好多例子,都运行不成功.最后找了个国外的,很简单的就解决了. log4net它已经定义的字段有 <commandText value=&q ...

  5. NLog自定义字段写入数据库表,示例

    //自定义字段写入NLog日志 private void saveNLog(InvokeLogModel model) { LogEventInfo ei = new LogEventInfo(); ...

  6. Log4net 自定义字段到数据库(二)

    这种方法比第一种方法麻烦些 Log4Net.config <?xml version="1.0" encoding="utf-8" ?> <c ...

  7. Oracle:ODP&period;NET Managed 小试牛刀

    “ODP.NET Managed”发布已经有一段时间了,近期正好有一个新项目,想尝试用一下,参考园子里的文章:<.NET Oracle Developer的福音——ODP.NET Managed ...

  8. PetaPoco利用ODP&period;NET Managed Driver连接Oracle

    大概几年之前用PetaPoco做过一个Oracle的项目,开发的时候还需要安装oracle的client,非常麻烦.调试好环境后,一直到项目结束都不敢重装系统.最近又有一个需求需要读取oracle,可 ...

  9. ODP&period;NET Managed 相关文章收集

      一.Oracle 对.net支持的一些基础知识了解介绍. 1.早年的时候,微软自己做的有 System.Data.OracleClient. 现在已经成了过期类了.性能等都不是很好. 2.Orac ...

随机推荐

  1. css&sol;js&lpar;工作中遇到的问题&rpar;-3

    设置宽高比 使用padding/margin-top/bottom; 设置出教准确的自适应布局; 用于预加载图片; 关于数据库设置 添加extra对象用于扩展; 添加type类型; 对于字体 使用百分 ...

  2. SQL SERVER 中的行列转换小结

    1. 介绍说明 前段时间组内的小伙伴在升级维护项目中,经常涉及一些复杂的数据转换问题,让我去看下有些地方怎么处理,我发现好多都是涉及到行列转换的问题,处理起来经常会比较麻烦,借此也总结一下,方便以后的 ...

  3. 《C和指针》章节后编程练习解答参考——6&period;2

    <C和指针>——6.2 题目: 编写一个函数,删除源字符串中含有的子字符串部分. 函数原型: int del_substr(char *str, char const *substr); ...

  4. jQuery validate入门

    <html> <head> <meta charset="utf8"></meta> </head> <body& ...

  5. Vue&period;use自定义自己的全局组件

    通常我们在vue里面使用别人开发的组件,第一步就是install,第二步在main.js里面引入,第三步Vue.use这个组件.今天我简单的也来use一个自己的组件. 这里我用的webpack-sim ...

  6. Sql Server 里的向上取整、向下取整、四舍五入取整的实例!

    http://blog.csdn.net/dxnn520/article/details/8454132 =============================================== ...

  7. 读书笔记:《HTML5开发手册》-- 现存元素的变化

    继续学习HTML5语义化的内容,今天主要介绍一下,HTML5之前的元素经HTML5规范后的语义及一些使用示例. 一.cite HTML5对cite元素的定义进行了很大的修改,在HTML4中,cite元 ...

  8. python之Django学习笔记(三)---URL调度&sol;URL路由

    在django中,用户发起url请求消息首先到工程的urls.py中查找是否有匹配的url路径 刚创建好的工程中urls.py只有下面几行代码: from django.contrib import ...

  9. java 执行https的请求

    普通的get和post请求只能执行http的请求,遇到的了https的就歇菜了,需要SSL安全证书处理. 该方法只能用jdk1.7和1.8进行处理,jdk1.6会报Could not generate ...

  10. 2018年天梯赛LV2题目汇总小结

    Ⅰ.L2-1 分而治之---邻接表 分而治之,各个击破是兵家常用的策略之一.在战争中,我们希望首先攻下敌方的部分城市,使其剩余的城市变成孤立无援,然后再分头各个击破.为此参谋部提供了若干打击方案.本题 ...