使用log4net记录日志到数据库(含有自定义属性)
记录日志是管理系统中对用户行为的一种监控与审核,asp.net中记录日志的方式有很多种,这里我只介绍一下最近用到的log4net,关于他的具体介绍网上有很多,我讲一下他的用法。
第一步:在配置文件中的<configSections>节添加下面一句话
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
第二步:在<configuration>节中添加如下内容
< log4net>
<root >
<level value="Debug"/>
<appender-ref ref="ADONetAppender"/>
</root>
<logger name="myLogger">
<level value="Debug"/>
<appender-ref ref="ADONetAppender"/>
</logger>
//关于上边root到logger这块,如果同时出现,有可能会出现重复插入记录的情况,那么就需要改一下代码,把上面两段代码改成如下一段代码,如下:
<root >
<level value="Debug" name="myLogger"/>
<appender-ref ref="ADONetAppender"/>
</root>
//下面就是对插入到数据库一些基本设置和基本字段设置
<appender name="ADONetAppender" type="log4net.Appender.ADONetAppender,log4net">
<!--BufferSize为缓冲区大小,只有日志记录超10条才会一块写入到数据库-->
<bufferSize value="10"/>
<!--或写为<param name="BufferSize" value="10" />-->
<!--引用-->
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<!--连接数据库字符串-->
<connectionString value="Data Source=.;Initial Catalog=audit;Persist Security Info=True;User ID=sa;Password=123;MultipleActiveResultSets=True"/>
<!--插入到表Log-->
<commandText value="INSERT INTO T_AUDITINFO ([EVENTTYPE],[TIMESTAMP],[EVENTCATEGORY],[EVENT_ID],[COMPUTERNAME],[MAC_ADDRESS],[USERNAME],[SOURCETYPE],[SOURCE],[DESCRIPTION],[COLLECTDATE]) VALUES (@Event_Type,@log_date, @EventCategory, @Event_ID, @ComputerName,@Mac_Address,@UserName,@SourceType,@Source,@Description,@CollectDate)"/>
<!--日志类型,这里均为3-->
<parameter>
<parameterName value="@Event_Type"/>
<dbType value="Int32"/>
<layout type="LogComponent.MyLayout, LogComponent">
<param name="ConversionPattern" value="%property{Event_Type}"/>//注意这里,当用到property时,就表明这是用户自定义的字段属性啦,是log4net中所没有提供的字段。其中MyLayout是自定义属性所在的类,
LogComponent是类所在的命名空间,这是我们自己要写的部分,将在下面介绍。
</layout>
</parameter>
<!--日志记录时间,RawTimeStampLayout为默认的时间输出格式 -->
<parameter>
<parameterName value="@log_date"/>
<dbType value="DateTime"/>
<layout type="log4net.Layout.RawTimeStampLayout"/>//这里呢是获取log4net中提供的日志时间
</parameter>
<!--日志分类描述-->
<parameter>
<parameterName value="@EventCategory"/>
<dbType value="String"/>
<size value="50"/>
<layout type="LogComponent.MyLayout, LogComponent">
<param name="ConversionPattern" value="%property{EventCategory}"/>
</layout>
</parameter>
<!--日志分类号-->
<parameter>
<parameterName value="@Event_ID"/>
<dbType value="Int32"/>
<layout type="LogComponent.MyLayout, LogComponent">
<param name="ConversionPattern" value="%property{Event_ID}"/>
</layout>
</parameter>
<!--计算机IP-->
<parameter>
<parameterName value="@ComputerName"/>
<dbType value="String"/>
<size value="50"/>
<layout type="LogComponent.MyLayout, LogComponent">
<param name="ConversionPattern" value="%property{ComputerName}"/>
</layout>
</parameter>
<!--计算机Mac信息-->
<parameter>
<parameterName value="@Mac_Address"/>
<dbType value="String"/>
<size value="50"/>
<layout type="LogComponent.MyLayout, LogComponent">
<param name="ConversionPattern" value="%property{Mac_Address}"/>
</layout>
</parameter>
<!--登陆系统用户名-->
<parameter>
<parameterName value="@UserName"/>
<dbType value="String"/>
<size value="50"/>
<layout type="LogComponent.MyLayout, LogComponent">
<param name="ConversionPattern" value="%property{UserName}"/>
</layout>
</parameter>
<!--事件来源类型,这里默认为Rier-->
<parameter>
<parameterName value="@SourceType"/>
<dbType value="String"/>
<size value="20"/>
<layout type="LogComponent.MyLayout, LogComponent">
<param name="ConversionPattern" value="%property{SourceType}"/>
</layout>
</parameter>
<!--事件来源-->
<parameter>
<parameterName value="@Source"/>
<dbType value="String"/>
<size value="50"/>
<layout type="LogComponent.MyLayout, LogComponent">
<param name="ConversionPattern" value="%property{Source}"/>
</layout>
</parameter>
<!--事件描述-->
<parameter>
<parameterName value="@Description"/>
<dbType value="String"/>
<size value="500"/>
<layout type="LogComponent.MyLayout, LogComponent">
<param name="ConversionPattern" value="%property{Description}"/>
</layout>
</parameter>
<!--日志收集时间-->
<parameter>
<parameterName value="@CollectDate"/>
<dbType value="DateTime"/>
<layout type="log4net.Layout.RawTimeStampLayout"/>
</parameter>
</appender>
</log4net>
第三步:自定义类,这些类呢包含将要插入数据库中的自定义字段
命名空间为 LogComponent 包含3个类:LogContent.cs、 MyLayout.cs 、MyMessagePatternConverter .cs
第一个类 LogContent.cs 包含了所有的自定字段属性
using System;
using System.Data;
using System.Configuration;
using System.Web;
/// <summary>
/// LogContent 的摘要说明
/// </summary>
public class LogContent
{
public LogContent(int eventType,string eventCategory,int eventID,string computerName,string macAddress,string userName,string sourceType,string source,string description)
{
_event_Type = eventType;
_eventCategory = eventCategory;
_event_ID = eventID;
_computerName = computerName;
_mac_Address = macAddress;
_userName = userName;
_sourceType = sourceType;
_source = source;
_description = description;
}
int _event_Type;
/// <summary>
/// 时间类型 均为3
/// </summary>
public int Event_Type
{
get { return _event_Type; }
set { _event_Type = value; }
}
string _eventCategory;
/// <summary>
/// 日志分类描述,自定义
/// </summary>
public string EventCategory
{
get { return _eventCategory; }
set { _eventCategory = value; }
}
int _event_ID;
/// <summary>
/// 日志分类号
/// </summary>
public int Event_ID
{
get { return _event_ID; }
set { _event_ID = value; }
}
string _computerName;
/// <summary>
/// 计算机IP
/// </summary>
public string ComputerName
{
get { return _computerName; }
set { _computerName = value; }
}
string _mac_Address;
/// <summary>
/// 计算机Mac地址
/// </summary>
public string Mac_Address
{
get { return _mac_Address; }
set { _mac_Address = value; }
}
string _userName;
/// <summary>
/// 系统登陆用户
/// </summary>
public string UserName
{
get { return _userName; }
set { _userName = value; }
}
string _sourceType;
/// <summary>
/// Rier
/// </summary>
public string SourceType
{
get { return _sourceType; }
set { _sourceType = value; }
}
string _source;
/// <summary>
/// Rier Recorder audit
/// </summary>
public string Source
{
get { return _source; }
set { _source = value; }
}
string _description;
/// <summary>
/// 日志描述信息
/// </summary>
public string Description
{
get { return _description; }
set { _description = value; }
}
}
第二个类 MyLayout.cs 把我们定义的属性转换为log4net所能识别的属性
using System;
using System.Collections.Generic;
using System.Text;
using log4net.Layout.Pattern;
using log4net.Layout;
using log4net.Core;
using System.Reflection;
namespace LogComponent
{
class MyLayout:PatternLayout
{
public MyLayout()
{
this.AddConverter("property", typeof(MyMessagePatternConverter));
}
}
}
第三个类
using System;
using System.Collections.Generic;
using System.Text;
using log4net.Layout.Pattern;
using log4net.Layout;
using log4net.Core;
using System.Reflection;
namespace LogComponent
{
class MyMessagePatternConverter:PatternLayoutConverter
{
protected override void Convert(System.IO.TextWriter writer, log4net.Core.LoggingEvent loggingEvent)
{
if (Option != null)
{
// Write the value for the specified key
WriteObject(writer, loggingEvent.Repository, LookupProperty(Option, loggingEvent));
}
else
{
// Write all the key value pairs
WriteDictionary(writer, loggingEvent.Repository, loggingEvent.GetProperties());
}
//if (Option != null)
//{
// // Write the value for the specified key
// WriteObject(writer, loggingEvent.Repository, loggingEvent.LookupProperty(Option));
//}
//else
//{
// // Write all the key value pairs
// WriteDictionary(writer, loggingEvent.Repository, loggingEvent.GetProperties());
//}
}
/// <summary>
/// 通过反射获取传入的日志对象的某个属性的值
/// </summary>
/// <param name="property"></param>
/// <returns></returns>
private object LookupProperty(string property, log4net.Core.LoggingEvent loggingEvent)
{
object propertyValue = string.Empty;
PropertyInfo propertyInfo = loggingEvent.MessageObject.GetType().GetProperty(property);
if (propertyInfo != null)
propertyValue = propertyInfo.GetValue(loggingEvent.MessageObject, null);
return propertyValue;
}
}
}
代码页
记得在该项目中添加log4net引用
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using LogComponent;
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
log4net.ILog log = log4net.LogManager.GetLogger("myLogger");
log.Info(new LogContent(3,"登陆系统",1,"127.0.0.1","111111","mhy","11111","11111111","登陆成功"));
}
}
转载于:https://www.cnblogs.com/goody9807/archive/2010/10/29/1864581.html
使用log4net记录日志到数据库(含有自定义属性)相关推荐
- asp.net mvc中用 log4net记录日志到数据库中
1.log4net官网配置相关,创建数据库 http://logging.apache.org/log4net/release/config-examples.html CREATE TABLE [d ...
- C#使用log4net记录日志
1.下载 log4net 右键引用,选择 管理NuGet程序包,选择浏览,输入log4net,然后点击下载 2.在App.config中输入内容(不存在自己创建) <?xml version=& ...
- log4net保存到数据库系列二:独立配置文件中配置log4net
园子里面有很多关于log4net保存到数据库的帖子,但是要动手操作还是比较不易,从头开始学习log4net数据库日志一.WebConfig中配置log4net 一.WebConfig中配置log4ne ...
- Windows服务使用log4net记录日志
该文章是系列文章 基于.NetCore和ABP框架如何让Windows服务执行Quartz定时作业 的其中一篇. 比较流行的日志组件有以下四种,Topshelf都有相应的组件提供 log4net NL ...
- .NET c#使用Log4net记录日志
log4net记录日志 记录一个简单的加法案例: 第一步下载log4net 下载地址:http://logging.apache.org/log4net/download_log4net.cgi 同时 ...
- 使用log4net记录日志到MySQL中 (转)
http://www.cnblogs.com/kongxx/archive/2005/10/09/251073.aspx 在log4net是.net平台中日志记录的开源工具包,其中包括了很多记录日志的 ...
- ASP.NET+MVC+使用+Log4net+记录日志笔记
前言: 记录系统中的日志,是一个好的项目产品必备的一个环节.每一个产品最终的目的都是要交予客户使用,因为程序员代码的开发水平参差不齐,Bug就成为了项目运维成本最大的因素之一.如何降低项目运维的成本呢 ...
- 磨刀不误砍柴工—Exceptionless搭配log4net记录日志
Exceptionless专注于.net平台提供实时错误和日志报告.主要包括:错误通知.智能分组异常.详细错误报告堆栈跟踪.支持离线.UI查看重要错误和确定优先级.仪表板上的统计信息和趋势.对异常标记 ...
- ASP.NET MVC 使用 Log4net 记录日志
Log4net 介绍 Log4net 是 Apache 下一个开放源码的项目,它是Log4j 的一个克隆版.我们可以控制日志信息的输出目的地.Log4net中定义了多种日志信息输出模式.它可以根据需要 ...
最新文章
- 美国波特兰市禁用人脸识别,被违规监控可获赔1000美元
- 你对Java网络编程了解的如何?Java BIO 网络编程 | Netty 前期知识
- java方法区对象类型_浅谈Java内存区域与对象创建过程
- linux中的集线器、交换机、路由器及组网
- 游戏入口点GameEntryPoint
- (转)使用JDK中的Proxy技术实现AOP功能
- 23、90秒快速“读懂”STP(生成树)工作原理
- python pep8_Python 代码风格 和 PEP8
- ta-lib依赖安装问题
- CentOS 6.2目录服务之LDAP(一)
- 【图像去噪】基于matlab GUI多种滤波器图像去噪【含Matlab源码 1778期】
- 高等数学学习笔记——第十讲——子数列与聚点原理(1. 数列收敛的归并性)
- Proteus进行单片机仿真(一)
- 元宇宙相关的前端技术
- Gif动图体积过大如何缩小?仅需三步教你在线压缩gif
- k8s集群安装traefik 2.x (保证成功版)
- 拨号连接显示服务器断开连接,弹出拨号连接的解决方法【详细介绍】
- Idea,webStorm工具栏显示,添加快捷方式建文件
- 最简单的人脸检测(免费调用百度AI开放平台接口)
- 四元数船舶领域Quaternion ship domain
热门文章
- MATLAB学习笔记(十六)
- linux没有那个文件或目录_Linux安装python faiss模块
- python获取局域网在线主机_pythond的icmp广播报获取局域网主机IP
- python自关联_django自关联,auth模块
- 二叉树遍历代码_二叉树的题,就那几个框架,枯燥至极
- 新建站点的mysql数据库_lAMP下新建维护站点全过程
- 数据库封装 sql server mysql_mysql操作数据库进行封装实现增删改查功能
- java rmi 多ip_在rmi连接中客户端指定一个ip地址,但程序执行中却转换成另一个地址...
- oracle触发器记录所有dml,Oracle DML类型触发器
- python networkx使用案例_在有向图networkx的大型网络实例上,什么是最快的迭代?...