Log4net 自定义字段 写入Oracle 使用ODP.NET Managed驱动
一、环境说明:
开发工具: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://stackoverflow.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驱动的更多相关文章
- log4net自定义字段写入SqlServer数据库 ASP.net
首先申明,本示例经过本作者亲自试验通过,可以运行 第一步 编写log4net配置文件 此处为Log.xml,该文件放在与Web.config平级的位置 <?xml version="1 ...
- NLog 自定义字段 写入 oracle
1.通过Nuget安装NLog 下载,简单入门 请参照 我刚才转的几篇文章,下面我直接贴代码 2.建表语句 create table TBL_LOG ( id ) not null, appname ...
- [转]NLog 自定义字段 写入 oracle
本文转自:http://www.cnblogs.com/skyapplezhao/p/5690695.html 1.通过Nuget安装NLog 下载,简单入门 请参照 我刚才转的几篇文章,下面我直接贴 ...
- Log4net 自定义字段到数据库
今天要求做个log4net自定义字段到数据库,在网上找了好多例子,都运行不成功.最后找了个国外的,很简单的就解决了. log4net它已经定义的字段有 <commandText value=&q ...
- NLog自定义字段写入数据库表,示例
//自定义字段写入NLog日志 private void saveNLog(InvokeLogModel model) { LogEventInfo ei = new LogEventInfo(); ...
- Log4net 自定义字段到数据库(二)
这种方法比第一种方法麻烦些 Log4Net.config <?xml version="1.0" encoding="utf-8" ?> <c ...
- Oracle:ODP.NET Managed 小试牛刀
“ODP.NET Managed”发布已经有一段时间了,近期正好有一个新项目,想尝试用一下,参考园子里的文章:<.NET Oracle Developer的福音——ODP.NET Managed ...
- PetaPoco利用ODP.NET Managed Driver连接Oracle
大概几年之前用PetaPoco做过一个Oracle的项目,开发的时候还需要安装oracle的client,非常麻烦.调试好环境后,一直到项目结束都不敢重装系统.最近又有一个需求需要读取oracle,可 ...
- ODP.NET Managed 相关文章收集
一.Oracle 对.net支持的一些基础知识了解介绍. 1.早年的时候,微软自己做的有 System.Data.OracleClient. 现在已经成了过期类了.性能等都不是很好. 2.Orac ...
随机推荐
- 如何过滤php中危险的HTML代码
用php过滤html里可能被利用来引入外部危险内容的代码.有些时候,需要让用户提交html内容,以便丰富用户发布的信息,当然,有些可能造成显示页面布局混乱的代码也在过滤范围内. 以下是引用片段: #用 ...
- 基于docker部署的微服务架构(四): 配置中心
原文:http://www.jianshu.com/p/b17d65934b58%20 前言 在微服务架构中,由于服务数量众多,如果使用传统的配置文件管理方式,配置文件分散在各个项目中,不易于集中管理 ...
- Python爬虫(六)
源码: import requests import re from my_mysql import MysqlConnect # 获取问答信息 def get_contents(page,heade ...
- Maven编译失败,提示No compiler is provided in this enviroment. Perhaps you are running on a JRE rathen a JDK ?
用maven对项目进行构建时,提示No compiler is provided in this enviroment. Perhaps you are running on a JRE rathen ...
- 报错:org.springframework.http.converter.json.MappingJacksonHttpMessageConverter
org.springframework.http.converter.json.MappingJacksonHttpMessageConverter 1.错误描述 严重: Servlet /hux ...
- 第4章 Vim编辑器与Shell命令脚本
章节简述: 本章节将教给您如何使用Vim编辑器来编写文档.配置主机名称.网卡参数以及yum仓库 ,熟练使用各个模式和命令快捷键. 我们可以通过Vim编辑器将Linux命令放入合适的逻辑测试语句(if. ...
- 【BZOJ2792】[Poi2012]Well 二分+双指针法
[BZOJ2792][Poi2012]Well Description 给出n个正整数X1,X2,...Xn,可以进行不超过m次操作,每次操作选择一个非零的Xi,并将它减一. 最终要求存在某个k满足X ...
- Python--上传文件和下载文件
#!/usr/bin/env python# -*- coding: utf-8 -*-# @Time : 2017/12/28 13:56# @Author : Aries# @Site : # @ ...
- poj2826 An Easy Problem?!【计算几何】
含[三点坐标计算面积].[判断两线段是否有交点].[求线段交点]模板 An Easy Problem?! Time Limit: 1000MS Memory Limit: 65536K Tot ...
- HTML5跨平台开发环境配置
http://hi.baidu.com/kuntakinte/item/1bbd3759b4901a3695eb050c