如何计算hibernate在一个Grails请求中执行了多少SQL查询?
我需要用一个非常慢的请求调试Grails应用程序。我有SQL日志记录,但希望在不手动计算SQL查询的情况下查看SQL查询的数量如何计算hibernate在一个Grails请求中执行了多少SQL查询?,sql,hibernate,grails,logging,Sql,Hibernate,Grails,Logging,我需要用一个非常慢的请求调试Grails应用程序。我有SQL日志记录,但希望在不手动计算SQL查询的情况下查看SQL查询的数量 debug 'org.hibernate.SQL' trace 'org.hibernate.type' 对于eaxmple,在每个请求后有以下行(其中x是对SQL server进行的所有查询的数量): [2012-10-04 13:41:45049][LoggingFilters]信息-请求在8296毫秒内完成,并生成了x条SQL语句 谷歌搜索一番之后,
debug 'org.hibernate.SQL'
trace 'org.hibernate.type'
对于eaxmple,在每个请求后有以下行(其中x是对SQL server进行的所有查询的数量):
[2012-10-04 13:41:45049][LoggingFilters]信息-请求在8296毫秒内完成,并生成了x条SQL语句
谷歌搜索一番之后,Grails似乎不可能做到这一点,所以MySQL可能会提供信息?在Grails中使用
loggingSql
dataSource {
dbCreate = "update" // one of 'create', 'create-drop','update'
url = "jdbc:postgresql://localhost:5432/demodb"
loggingSql = true
}
您会注意到Grails使用的所有SQL语句都将被记录。您是否考虑过一些低技术的解决方案,比如通过
wc-l
运行输出?您可以通过使用过滤器和Hibernate统计信息来实现。
在conf文件夹中创建ExampleFilters.groovy类。这是本课程的内容:
import org.hibernate.stat.Statistics
class ExampleFilters {
def sessionFactory
def filters = {
// your filters here
logHibernateStats(controller: '*', action: '*') {
before = {
Statistics stats = sessionFactory.statistics;
if(!stats.statisticsEnabled) {stats.setStatisticsEnabled(true)}
}
afterView = {
Statistics stats = sessionFactory.getStatistics()
double queryCacheHitCount = stats.getQueryCacheHitCount();
double queryCacheMissCount = stats.getQueryCacheMissCount();
double queryCacheHitRatio = (queryCacheHitCount / ((queryCacheHitCount + queryCacheMissCount) ?: 1))
println """
######################## Hibernate Stats ##############################################
Transaction Count:${stats.transactionCount}
Flush Count:${stats.flushCount}
Total Collections Fetched:${stats.collectionFetchCount}
Total Collections Loaded:${stats.collectionLoadCount}
Total Entities Fetched:${stats.entityFetchCount}
Total Entities Loaded:${stats.entityFetchCount}
Total Queries:${stats.queryExecutionCount}
queryCacheHitCount:${queryCacheHitCount}
queryCacheMissCount:${queryCacheMissCount}
queryCacheHitRatio:${queryCacheHitRatio}
######################## Hibernate Stats ##############################################
"""
stats.clear()
}
}
}
}
有关各种Hibernate统计信息的更多信息,请阅读本文:
还请注意,使用它会对性能产生影响,因此它实际上应该只在开发环境中使用。正如Burt Beckwith在其博客文章“Stuff I Learn Consulting”中所说的那样 SQL日志记录 有两种方法可以查看查询的SQL输出;在DataSource.groovy中添加logSql=true并配置Log4j记录器。Log4j方法更加灵活,因为它不仅仅转储到stdout,还可以路由到文件或其他appender,并方便地启用和禁用。但事实证明,切换logSql控制台日志记录很容易。获取对sessionFactory bean的引用(例如,使用def sessionFactory的依赖注入),并使用
sessionFactory.settings.sqlStatementLogger.logToStdout = true
and off with
sessionFactory.settings.sqlStatementLogger.logToStdout = false
是的,我已经启用了loggingSql。我需要的是最后SQL语句的计数。不幸的是hibernate没有在日志中每行打印查询。但您可以计算字符串“select”的出现次数。当然,您必须在每个会话之间截断日志文件。但这是一个解决办法!谢谢这正是我要找的资源