Skip to content
This repository
tree: 18d569232e
Fetching contributors…

Cannot retrieve contributors at this time

file 334 lines (300 sloc) 11.526 kb
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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
/*
* Copyright 2010 WorldWide Conferencing, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package net.liftweb {
package common {
  
import _root_.org.slf4j.{MDC => SLF4JMDC, Marker, Logger => SLF4JLogger, LoggerFactory}

object Logger {
  private[common] lazy val checkConfig: Boolean = {
    setup.foreach {_()};
    true
  }
  
  /**
* This function, if set, will be called before any loggers are created
*
* Useful for initializing the logging backend with a non-default configuration
*
* Helpers exists for log4j & logback:
*
* Logger.setup = Full(Log4j.withFile(url)
*
* or
*
* Logger.setup = Full(Logback.withFile(url))
*
*/
  var setup: Box[() => Unit] = Empty
  
  def loggerNameFor(cls: Class[_]) = {
    val className = cls.getName
    if (className endsWith "$")
      className.substring(0, className.length - 1)
    else
      className
  }

  def apply(cls: Class[_]): Logger = if (checkConfig) new WrappedLogger(LoggerFactory.getLogger(loggerNameFor(cls))) else null
  def apply(name: String): Logger = if (checkConfig) new WrappedLogger(LoggerFactory.getLogger(name)) else null
  
 /**
* Set the Mapped Diagnostic Context for the thread and execute
* the function f
*
* Upon return, the MDC is cleared of the values passed (any
* MDC values that existed prior to this call remains)
*/
  def logWith[F](mdcValues: (String,Any)*)(f: => F): F = {
    val old = SLF4JMDC.getCopyOfContextMap
    MDC.put(mdcValues:_*)
    try {
      f
    } finally {
      if (old eq null)
        MDC.clear
      else
        SLF4JMDC.setContextMap(old)
    }
  }
}

/**
* The Mapped Diagnostics Context can hold values per thread and output them
* with each logged output.
*
* The logging backend needs to be configured to log these values
*/
object MDC {
  /**
* Put a (key,value) pair into the Mapped Diagnostic Context
*/
  def put(kvs: (String,Any)*) = {
    kvs foreach {v => SLF4JMDC.put(v._1, v._2.toString)}
  }

  /**
* Clear key from the Mapped Diagnostic Context
*/
  def remove(keys: String*) = {
    keys foreach {k => SLF4JMDC.remove(k)}
  }

  /**
* Clear all entries from the Mapped Diagnostic Context
*/
  def clear() = org.slf4j.MDC.clear
}

/**
* Logger is a thin wrapper on top of an SLF4J Logger
*
* The main purpose is to utilize Scala features for logging
*
* Note that the dynamic type of "this" is used when this trait is
* mixed in.
*
* This may not always be what you want. If you need the static type, you have to declare your
* own Logger:
*
* class MyClass {
* val logger = Logger(classOf[MyClass])
* }
*
*/
trait Logger {
  private lazy val logger: SLF4JLogger = _logger // removed @transient 'cause there's no reason for transient on val
  // changed to lazy val so it only gets initialized on use rather than on instantiation
  protected def _logger = if (Logger.checkConfig) LoggerFactory.getLogger(Logger.loggerNameFor(this.getClass)) else null
  
  def assertLog(assertion: Boolean, msg: => String) = if (assertion) info(msg)

  /**
* Log the value of v with trace and return v. Useful for tracing values in expressions
*/
  def trace[T](msg: String, v: T): T = {
    logger.trace(msg+": "+v.toString)
    v
  }
 
  /**
* Trace a Failure. If the log level is trace and the Box is
* a Failure, trace the message concatenated with the Failure's message.
* If the Failure contains an Exception, trace that as well.
*/
  def trace(msg: => AnyRef, box: Box[_]): Unit = {
    if (logger.isTraceEnabled) {
      box match {
        case Failure(fmsg, Full(e), _) => trace(String.valueOf(msg)+": "+
                                                fmsg: AnyRef, e: Throwable)
        case Failure(fmsg, _, _) => trace(String.valueOf(msg)+": "+fmsg)
        case _ =>
      }
    }
  }


  def trace(msg: => AnyRef) = if (logger.isTraceEnabled) logger.trace(String.valueOf(msg))
  def trace(msg: => AnyRef, t: Throwable) = if (logger.isTraceEnabled) logger.trace(String.valueOf(msg), t)
  def trace(msg: => AnyRef, marker: Marker) = if (logger.isTraceEnabled) logger.trace(marker,String.valueOf(msg))
  def trace(msg: => AnyRef, t: Throwable, marker: => Marker) = if (logger.isTraceEnabled) logger.trace(marker,String.valueOf(msg), t)
  def isTraceEnabled = logger.isTraceEnabled

  /**
* Debug a Failure. If the log level is debug and the Box is
* a Failure, debug the message concatenated with the Failure's message.
* If the Failure contains an Exception, debug that as well.
*/
  def debug(msg: => AnyRef, box: Box[_]): Unit = {
    if (logger.isDebugEnabled) {
      box match {
        case Failure(fmsg, Full(e), _) => debug(String.valueOf(msg)+": "+
                                                fmsg, e)
        case Failure(fmsg, _, _) => debug(String.valueOf(msg)+": "+fmsg)
        case _ =>
      }
    }
  }
 
  
  def debug(msg: => AnyRef) = if (logger.isDebugEnabled) logger.debug(String.valueOf(msg))
  def debug(msg: => AnyRef, t: Throwable) = if (logger.isDebugEnabled) logger.debug(String.valueOf(msg), t)
  def debug(msg: => AnyRef, marker: Marker) = if (logger.isDebugEnabled) logger.debug(marker, String.valueOf(msg))
  def debug(msg: => AnyRef, t: Throwable, marker: Marker) = if (logger.isDebugEnabled) logger.debug(marker, String.valueOf(msg), t)
  def isDebugEnabled = logger.isDebugEnabled
  
  /**
* Info a Failure. If the log level is info and the Box is
* a Failure, info the message concatenated with the Failure's message.
* If the Failure contains an Exception, info that as well.
*/
  def info(msg: => AnyRef, box: Box[_]): Unit = {
    if (logger.isInfoEnabled) {
      box match {
        case Failure(fmsg, Full(e), _) => info(String.valueOf(msg)+": "+
                                                fmsg, e)
        case Failure(fmsg, _, _) => info(String.valueOf(msg)+": "+fmsg)
        case _ =>
      }
    }
  }
  def info(msg: => AnyRef) = if (logger.isInfoEnabled) logger.info(String.valueOf(msg))
  def info(msg: => AnyRef, t: => Throwable) = if (logger.isInfoEnabled) logger.info(String.valueOf(msg), t)
  def info(msg: => AnyRef, marker: Marker) = if (logger.isInfoEnabled) logger.info(marker,String.valueOf(msg))
  def info(msg: => AnyRef, t: Throwable, marker: Marker) = if (logger.isInfoEnabled) logger.info(marker,String.valueOf(msg), t)
  def isInfoEnabled = logger.isInfoEnabled
  
  /**
* Warn a Failure. If the log level is warn and the Box is
* a Failure, warn the message concatenated with the Failure's message.
* If the Failure contains an Exception, warn that as well.
*/
  def warn(msg: => AnyRef, box: Box[_]): Unit = {
    if (logger.isWarnEnabled) {
      box match {
        case Failure(fmsg, Full(e), _) => warn(String.valueOf(msg)+": "+
                                                fmsg, e)
        case Failure(fmsg, _, _) => warn(String.valueOf(msg)+": "+fmsg)
        case _ =>
      }
    }
  }
  def warn(msg: => AnyRef) = if (logger.isWarnEnabled) logger.warn(String.valueOf(msg))
  def warn(msg: => AnyRef, t: Throwable) = if (logger.isWarnEnabled) logger.warn(String.valueOf(msg), t)
  def warn(msg: => AnyRef, marker: Marker) = if (logger.isWarnEnabled) logger.warn(marker,String.valueOf(msg))
  def warn(msg: => AnyRef, t: Throwable, marker: Marker) = if (logger.isWarnEnabled) logger.warn(marker,String.valueOf(msg), t)
  def isWarnEnabled = logger.isWarnEnabled
  
  /**
* Error a Failure. If the log level is error and the Box is
* a Failure, error the message concatenated with the Failure's message.
* If the Failure contains an Exception, error that as well.
*/
  def error(msg: => AnyRef, box: Box[_]): Unit = {
    if (logger.isErrorEnabled) {
      box match {
        case Failure(fmsg, Full(e), _) => error(String.valueOf(msg)+": "+
                                                fmsg, e)
        case Failure(fmsg, _, _) => error(String.valueOf(msg)+": "+fmsg)
        case _ =>
      }
    }
  }

  def error(msg: => AnyRef) = if (logger.isErrorEnabled) logger.error(String.valueOf(msg))
  def error(msg: => AnyRef, t: Throwable) = if (logger.isErrorEnabled) logger.error(String.valueOf(msg), t)
  def error(msg: => AnyRef, marker: Marker) = if (logger.isErrorEnabled) logger.error(marker,String.valueOf(msg))
  def error(msg: => AnyRef, t: Throwable, marker: Marker) = if (logger.isErrorEnabled) logger.error(marker,String.valueOf(msg), t)
  def isErrorEnabled = logger.isErrorEnabled
  
}

class WrappedLogger(l: SLF4JLogger) extends Logger {
  override def _logger = l
}

/**
* Mixin with a nested Logger
*/
trait Loggable {
  @transient protected val logger = Logger(this.getClass)
}

/**
* Mixin with a nested lazy Logger
*
* Useful for mixin to objects that are created before Lift has booted (and thus Logging is not yet configured)
*/
trait LazyLoggable {
  @transient protected lazy val logger = Logger(this.getClass)
}

/**
* Configuration helpers for the log4j logging backend
*/
object Log4j {
  import org.apache.log4j.{LogManager,PropertyConfigurator}
  import org.apache.log4j.xml.DOMConfigurator
  
  val defaultProps =
    """<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="appender" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.SimpleLayout"/>
</appender>
<root>
<priority value ="INFO"/>
<appender-ref ref="appender"/>
</root>
</log4j:configuration>
"""
  
  /**
* Configure with contents of the specified filed (either .xml or .properties)
*/
  def withFile(url: java.net.URL)() = {
    if (url.getPath.endsWith(".xml")) {
      val domConf = new DOMConfigurator
      domConf.doConfigure(url, LogManager.getLoggerRepository())
    } else
      PropertyConfigurator.configure(url)
  }
  /**
* Configure with the specified configuration. config must contain a valid XML document
*/
  def withConfig(config: String)() = {
    val domConf = new DOMConfigurator
    val is = new java.io.ByteArrayInputStream(config.getBytes("UTF-8"))
    domConf.doConfigure(is, LogManager.getLoggerRepository())
  }
  
  /**
* Configure with simple defaults
*/
  def withDefault() = withConfig(defaultProps)
}

/**
* Configuration helpers for the Logback logging backend
*/
object Logback {
  import ch.qos.logback.classic.LoggerContext;
  import ch.qos.logback.core.util.StatusPrinter;
  import ch.qos.logback.classic.joran.JoranConfigurator;

  /**
* Configure with contents of the specified XML filed
*/
  def withFile(url: java.net.URL)() = {
    val lc = LoggerFactory.getILoggerFactory().asInstanceOf[LoggerContext];
    val configurator = new JoranConfigurator();
    configurator.setContext(lc);
    // the context was probably already configured by default configuration rules
    lc.reset();
    configurator.doConfigure(url);
  }
}

}
}
Something went wrong with that request. Please try again.