Log4net自定义信息(变量或属性或字段)存入数据库 ,log4net 写日志到 Sql server 数据库 。.net4.0
扩展Log4net日志,支持自定义属性写入数据库。
本文所提及的方式,不是原创,方法都来自互联网,出处不详。增加了登录用户的ID,IP地址,MAC地址,日志分类(系统业务上需要的)
Log4net采用1.2.10版本
同时解决了Log4net使用现有数据库链接connectionStrings( Log4Net中使用系统本身的connectionString),
网上说log4net1.2.11版本以上支持connectionStringName,但是我使用这个版本,包括log4net1.12.13的时候,我的自定义属性使用不了。报错如下:
System.InvalidCastException was unhandled by user code
HResult=-2147467262
Message=无法将类型为“System.RuntimeType”的对象强制转换为类型“log4net.Util.ConverterInfo”。
Source=log4net
StackTrace:
在 log4net.Util.PatternParser.ProcessConverter(String converterName, String option, FormattingInfo formattingInfo)
在 log4net.Util.PatternParser.ParseInternal(String pattern, String[] matches)
在 log4net.Util.PatternParser.Parse()
没办法只有自己实现,在网上找到的,出处记不得了
///
/// http://issues.apache.org/jira/browse/LOG4NET-88
/// An appender for Log4Net that uses a database based on the connection string name.
///
public class Log4NetConnectionStringNameAdoNetAppender : AdoNetAppender
{
private static ILog _Log;
Log4net自定义字段,
internal sealed class UserNamePatternConverter : PatternLayoutConverter
{
override protected void Convert(TextWriter writer, LoggingEvent loggingEvent)
{
LogMessage logMessage = loggingEvent.MessageObject as LogMessage;
if (logMessage != null)
//将UserName作为日志信息输出
writer.Write(logMessage.UserName);
}
}
更具体的查看public class Log4NetCustomLayout : log4net.Layout.LayoutSkeleton
我的数据库表ms sql2008r2
USE [hotel]
GO
/****** Object: Table [dbo].[XTRZ] Script Date: 09/07/2014 22:11:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[XTRZ](
[ID] [int] IDENTITY(1,1) NOT NULL,
[USER] [varchar](40) NULL,
[IP] [varchar](32) NULL,
[MAC] [varchar](32) NULL,
[Type] [varchar](50) NULL,
[Message] [varchar](1000) NULL,
[Date] [datetime] NULL,
[LEVEL] [varchar](10) NULL,
[THREAD] [varchar](255) NULL,
[EXCEPTION] [varchar](1000) NULL,
[LOGGER] [varchar](255) NULL,
[Abstract] [varchar](128) NULL,
CONSTRAINT [PK_XTRZ] PRIMARY KEY NONCLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[XTRZ] ADD DEFAULT (getdate()) FOR [Date]
GO
log4net配置
>
具体代码:
http://download.csdn.net/detail/dacong/7877741
下载,需要5分
参考资料
How i can use the connectionString of the current website for log4Net instead of configuring
You can do that by inheriting AdoNetAppender.
This should be possible in version 1.2.11. Here is the link to the issue:
https://issues.apache.org/jira/browse/LOG4NET-88
log4net把自定义的变量写入数据库
Log4net如何增加自定义字段(三种方式):http://fqctyj.blog.163.com/blog/static/7084345520137910329773/