-
-
Save loganj/192001 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* Base trait for all classes that wants to be able use the logging infrastructure. | |
* | |
* @author <a href="http://jonasboner.com">Jonas Boné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é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