Creating an audit-event listener

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.

How to do it...

  1. Create a new console application project named AuditEventListener.
  2. Add a reference to our Eg.Core model from Chapter 1, along with NHibernate.dll and log4net.dll.
  3. Add an App.config with a standard NHibernate and log4net configuration.
  4. Just before the end of the 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>
  5. Add the following 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);
      }
    
    }
  6. Add the following event listener class:
    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;
      }
    
    }
  7. In Program.cs, configure NHibernate and log4net, and build a session factory just like we did in Chapter 2 and Chapter 3.
  8. Finally, in Main, add code to save a new entity, update it, and then delete it.
  9. Build and run your application.

How it works...

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.

Note

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.

There's more...

NHibernate provides the following events:

  • auto-flush
  • merge
  • create
  • create-onflush
  • delete
  • dirty-check
  • evict
  • flush
  • flush-entity
  • load
  • load-collection
  • lock
  • refresh
  • replicate
  • save
  • save-update
  • pre-update
  • update
  • pre-load
  • pre-delete
  • pre-insert
  • post-load
  • post-insert
  • post-update
  • post-delete
  • post-commit update
  • post-commit insert
  • post-commit delete
  • pre-collection recreate
  • pre-collection remove
  • pre-collection delete
  • post-collection recreate
  • post-collection remove
  • post-collection update

See also

  • Creating and changing stamping entities
  • Generating trigger-based auditing
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.79.241