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, we will show you how you can easily create an audit log to track changes to your 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 2, Models and Mappings.
  3. Install the NHibernate and log4net packages using the NuGet Package Manager Console by executing the following commands:
    Install-Package NHibernate
    Install-Package log4net
    
  4. Add an App.config with a standard NHibernate and log4net configuration.
  5. 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>
  6. Add the following IAuditLogger interface:
    public interface IAuditLogger 
    {
    
      void Insert(Entity entity);
      void Update(Entity entity);
      Void Delete(Entity entity); 
    
    }
  7. Add the following AuditLogger class:
    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);
      }
    
    }
  8. 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;
      }
    
    }
  9. In Program.cs, configure NHibernate and log4net, and build a session factory just as we did in Chapter 1, The Configuration and Schema and Chapter 3, Sessions and Transactions.
  10. Finally, in Main, add code to save a new entity, update it, and then delete it.
  11. 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

  • Creation and change stamping of entities
  • Generating trigger-based auditing
  • Using NHibernate Envers
..................Content has been hidden....................

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