Skip to content

Instantly share code, notes, and snippets.

@JoshClose
Created November 15, 2011 04:02
Show Gist options
  • Save JoshClose/1366100 to your computer and use it in GitHub Desktop.
Save JoshClose/1366100 to your computer and use it in GitHub Desktop.
Audit Trail with NHibernate Using a Custom log4net Appender
CREATE TABLE [dbo].[Audit]
(
[Id] INT NOT NULL IDENTITY,
[User] NVARCHAR( 100 ) NOT NULL,
[Trail] NVARCHAR( MAX ) NOT NULL,
[Created] DATETIME NOT NULL
)
ALTER TABLE [dbo].[Audit]
ADD CONSTRAINT [PK_Audit_Id]
PRIMARY KEY (Id)
public class NHibernateAuditAppender : AppenderSkeleton
{
private static IKernel kernel;
protected override void Append( LoggingEvent loggingEvent )
{
#if !DEBUG
if( loggingEvent.RenderedMessage.StartsWith( "SELECT" ) )
{
return;
}
#endif
var session = kernel.Get<ISession>();
var audit = new Audit
{
Created = DateTime.UtcNow,
Trail = loggingEvent.RenderedMessage,
User = Thread.CurrentPrincipal.Identity.Name
};
session.Save( audit );
}
}
public class NHibernateAuditAppender : AppenderSkeleton
{
private static IKernel kernel;
protected override void Append( LoggingEvent loggingEvent )
{
#if !DEBUG
if( loggingEvent.RenderedMessage.StartsWith( "SELECT" ) )
{
return;
}
#endif
var session = kernel.Get<ISession>();
var audit = new Audit
{
Created = DateTime.UtcNow,
Trail = loggingEvent.RenderedMessage,
User = Thread.CurrentPrincipal.Identity.Name
};
session.Save( audit );
}
public static void RegisterAppender( IKernel kernel )
{
NHibernateAuditAppender.kernel = kernel;
var repository = (Hierarchy)LogManager.GetRepository();
var appender = new NHibernateAuditAppender { Name = "NHibernateAuditAppender" };
var logger = (Logger)repository.GetLogger( "NHibernate.SQL" );
logger.Level = Level.Debug;
logger.Additivity = false;
logger.AddAppender( appender );
appender.ActivateOptions();
repository.Configured = true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment