forked from skinny-framework/skinny-framework
/
TimeLogging.scala
53 lines (46 loc) · 1.37 KB
/
TimeLogging.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package skinny.util
import skinny.SkinnyEnv
import skinny.logging.LoggerProvider
object TimeLogging extends TimeLogging
/**
* Time logging for the block.
*
* {{{
* class RootController extends ApplicationController {
* def doSomething = {
* Thread.sleep(10)
* "AAAA"
* }
*
* def index = {
* val result = warnElapsedTime(1) {
* doSomething
* }
* render("/root/index")
* }
* }}}
*/
trait TimeLogging extends LoggerProvider {
protected def stackTraceDepthForTimeLogging: Int = 5
def warnElapsedTime[A](millis: Long, additionalLines: => Seq[String] = Nil)(action: => A) = {
def where: String = {
s"""
|${Thread.currentThread.getStackTrace.drop(7).take(stackTraceDepthForTimeLogging).map { callee => s" ${callee}" }.mkString("\n")}
| ...
|""".stripMargin
}
val before = System.currentTimeMillis
val result = action
val after = System.currentTimeMillis
val elapsedMillis = after - before
def additionalInfo = if (additionalLines.isEmpty) "" else "\n" + additionalLines.map(s => " " + s).mkString("\n")
if (elapsedMillis >= millis) {
logger.warn(s"[SLOW EXECUTION DETECTED] Elapsed time: ${elapsedMillis} millis${additionalInfo}\n${where}")
} else {
if (!SkinnyEnv.isProduction()) {
logger.info(s"Elapsed time: ${elapsedMillis} millis${additionalInfo}\n${where}")
}
}
result
}
}