Note that there are some explanatory texts on larger screens.

plurals
  1. POscala self aware trait
    primarykey
    data
    text
    <p>I've made a Logging trait which encapsulates the details of a logging implementation, it's also nice and lazy so is efficient especially when a particular log level is not active.</p> <pre><code>/** * A SLF4J based logging trait */ trait Log { import org.slf4j.Logger import org.slf4j.LoggerFactory val loggedClazz: Class[_] lazy val logger: Logger = LoggerFactory.getLogger(loggedClazz.getClass) def logDebug(codeblock: =&gt; String) = { if (logger.isDebugEnabled) { logger.debug(codeblock) } } def logError(codeblock: =&gt; String) = { if (logger.isErrorEnabled) { logger.error(codeblock) } } def logInfo(codeblock: =&gt; String) = { if (logger.isInfoEnabled) { logger.info(codeblock) } } def logWarn(codeblock: =&gt; String) = { if (logger.isWarnEnabled) { logger.warn(codeblock) } } } </code></pre> <p>However it requires the class into which this trait is mixed-in to implement the following..</p> <pre><code>object MyServer extends Log { val loggedClazz = MyServer.getClass } </code></pre> <p>My question is, is it possible to somehow enable the Trait to know into which class it has been mixed into? Removing the need to do:</p> <pre><code> val loggedClazz = MyServer.getClass </code></pre> <p><strong>SOLUTION:</strong> Following the provided feedback, I rewrote the class in the following manner.</p> <pre><code>/** * A SLF4J based logging trait */ trait Log { import org.slf4j.Logger import org.slf4j.LoggerFactory lazy val logger: Logger = LoggerFactory.getLogger(getClass) def logDebug(codeblock: =&gt; String) = { if (logger.isDebugEnabled) { logger.debug(codeblock) } } def logError(codeblock: =&gt; String) = { if (logger.isErrorEnabled) { logger.error(codeblock) } } def logInfo(codeblock: =&gt; String) = { if (logger.isInfoEnabled) { logger.info(codeblock) } } def logWarn(codeblock: =&gt; String) = { if (logger.isWarnEnabled) { logger.warn(codeblock) } } } </code></pre> <p>Totally simple. When you do it right, first time ;)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload