Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kurtschindler/1114503 to your computer and use it in GitHub Desktop.
Save kurtschindler/1114503 to your computer and use it in GitHub Desktop.
NHibernate Glimpse Plugin - full source
http://www.headspring.com/2011/07/creating-a-glimpse-plugin-to-log-sql-generated-by-nhibernate
The following code is all that's required to implement a Glimpse plugin that renders the SQL generated by NHibernate. A full blog post describing this is at the link above.
1. Create a custom Log4Net appender:
-----------------------------------
public class NHibernateQueryAppender : AppenderSkeleton
{
protected override void Append(LoggingEvent loggingEvent)
{
//This part is trivial - you can collect the RenderedMessage (the SQL statement)
//several ways. SqlLogger is just a wrapper over the HttpContext.Items collection
SqlLogger.AddSql(loggingEvent.RenderedMessage);
}
}
3. Configure Log4Net in your web.config:
---------------------------------------
<log4net>
<appender name="GlimpseAppender" type="Headspring.Data.NHibernateQueryAppender, Headspring" />
<logger name="NHibernate.SQL">
<level value="DEBUG"/>
<appender-ref ref="GlimpseAppender" />
</logger>
</log4net>
3. Create the Glimpse Plugin:
----------------------------
[Glimpse.Core.Extensibility.GlimpsePluginAttribute()]
public class NHGlimpsePlugin : IGlimpsePlugin
{
public object GetData(HttpContextBase context)
{
var data = new List<object[]> { new[] { "Key", "Value" } };
data.Add(new object[] { "*count*", SqlLogger.Count });
foreach (var sqlString in SqlLogger.All())
{
data.Add(new object[] { "*sql*", sqlString });
}
return data;
}
public void SetupInit() { }
public string Name { get { return "NHibernate"; } }
}
4. The SqlLogger implementation:
-------------------------------
//Again, this is just a mechanism for the logger to log the SQL to, and the Glimpse plugin to retrieve the SQL from.
public static class SqlLogger
{
public static void AddSql(string sql)
{
SqlStatements.Add(sql);
}
public static IEnumerable<string> All()
{
return SqlStatements;
}
public static int Count { get { return SqlStatements.Count; } }
private static IList<string> SqlStatements
{
get
{
var statements = HttpContext.Current.Items["sql"] as List<string>;
if (statements == null)
{
statements = new List<string>();
HttpContext.Current.Items["sql"] = statements;
}
return statements;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment