Created
November 15, 2011 04:02
-
-
Save JoshClose/1366100 to your computer and use it in GitHub Desktop.
Audit Trail with NHibernate Using a Custom log4net Appender
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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