Auditing is another common security-related task. An audit log is an append-only record of changes in a system that allows you to trace a particular action back to its source. In this recipe, I'll show you how we can easily create an audit log to track changes to our entities.
AuditEventListener
.Eg.Core
model from Chapter 1, along with NHibernate.dll
and log4net.dll
.App.config
with a standard NHibernate and log4net configuration.sessionfactory
element, add the following three event elements:<event type="pre-insert"> <listener class="AuditEventListener.EventListener, AuditEventListener" /> </event> <event type="pre-update"> <listener class="AuditEventListener.EventListener, AuditEventListener" /> </event> <event type="pre-delete"> <listener class="AuditEventListener.EventListener, AuditEventListener" /> </event>
IAuditLogger
interface:public class AuditLogger : IAuditLogger { private readonly ILog log = LogManager.GetLogger(typeof(AuditLogger)); public void Insert(Entity entity) { log.DebugFormat("{0} #{1} inserted.", entity.GetType(), entity.Id); } public void Update(Entity entity) { log.DebugFormat("{0} #{1} updated.", entity.GetType(), entity.Id); } public void Delete(Entity entity) { log.DebugFormat("{0} #{1} deleted.", entity.GetType(), entity.Id); } }
public class EventListener : IPreInsertEventListener, IPreUpdateEventListener, IPreDeleteEventListener { private readonly IAuditLogger _logger; public EventListener() : this(new AuditLogger()) { } public EventListener(IAuditLogger logger) { _logger = logger; } public bool OnPreInsert(PreInsertEvent e) { _logger.Insert(e.Entity as Entity); return false; } public bool OnPreUpdate(PreUpdateEvent e) { _logger.Update(e.Entity as Entity); return false; } public bool OnPreDelete(PreDeleteEvent e) { _logger.Delete(e.Entity as Entity); return false; } }
Program.cs
, configure NHibernate and log4net, and build a session factory just like we did in Chapter 2 and Chapter 3.Main
, add code to save a new entity, update it, and then delete it.NHibernate uses an event model to allow applications to hook into the NHibernate pipeline and change behavior. In this case, we simply write a message to the log4net log whenever an entity is inserted, updated, or deleted. The pre-insert
, pre-update
, and pre-delete
event listeners are called just before each change. We set these events with the event
element in our NHibernate configuration. They can also be set programmatically through the Configuration
object.
Log4net includes appenders capable of writing to different types of permanent storage, such as files and databases. We can use active context properties to record additional information such as the user who caused the change. More information, about these advanced log4net configurations is available in the log4net manual at http://logging.apache.org/log4net.
NHibernate provides the following events: