Skip to content

Instantly share code, notes, and snippets.

@loganj
Forked from jboner/LoggableException.scala
Created September 23, 2009 13:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loganj/192001 to your computer and use it in GitHub Desktop.
Save loganj/192001 to your computer and use it in GitHub Desktop.
/**
* Base trait for all classes that wants to be able use the logging infrastructure.
*
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
trait Logging {
@transient var log = Logger.get(this.getClass.getName)
}
/**
* LoggableException is a subclass of Exception and can be used as the base exception
* for application specific exceptions.
* <p/>
* It keeps track of the exception is logged or not and also stores the unique id,
* so that it can be carried all along to the client tier and displayed to the end user.
* The end user can call up the customer support using this number.
*
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
class LoggableException(message: String) extends RuntimeException(message) with Logging {
private val uniqueId = getExceptionID
private var originalException: Option[Exception] = None
private var isLogged = false
def this(baseException: Exception) = {
this("")
originalException = Some(baseException)
}
def logException = synchronized {
if (!isLogged) {
log.error("Logged Exception [%s] %s", uniqueId, getStackTraceAsString)
isLogged = true
}
}
def getExceptionID: String = {
val hostname = try {
InetAddress.getLocalHost.getHostName
} catch {
case e: UnknownHostException =>
log.error("Could not get hostname to generate loggable exception")
"N/A"
}
hostname + "_" + System.currentTimeMillis
}
def getStackTraceAsString: String = {
val sw = new StringWriter
val pw = new PrintWriter(sw)
originalException match {
case Some(e) => e.printStackTrace(pw)
case None => printStackTrace(pw)
}
sw.toString
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment