Play's logging API

Play exposes the logging API through play.api.Logger. Let's have a look at the class and object definition of it:

class Logger(val logger: Slf4jLogger) extends LoggerLike

object Logger extends LoggerLike {

  ...
  val logger = LoggerFactory.getLogger("application")

  def apply(name: String): Logger = new Logger(LoggerFactory.getLogger(name))

  def apply[T](clazz: Class[T]): Logger = new Logger(LoggerFactory.getLogger(clazz))

  ...

}

The LoggerLike trait is just a wrapper over Slf4jLogger. By default, all application logs are mapped to Logger with the application name and the Play-related logs are mapped to Logger with the Play name.

After importing play.api.Logger, we can use the default logger or define a custom one in these ways:

  • By using a default logger:
    import play.api.Logger
    object Task{
      def delete(id:Long) = {
        logger.debug(s"deleting task with id $id")
        ...
      }
    }
  • By using a logger with its class name:
    import play.api.Logger
    object Task{
      private lazy val taskLogger = Logger(getClass)
      def delete(id:Long) = {
        taskLogger.debug(s"deleting task with id $id")
        ...
      }
    }
  • By using a logger with its custom name:
    import play.api.Logger
    object Task{
      private lazy val taskLogger = Logger("application.model")
      def delete(id:Long) = {
        taskLogger.debug(s"deleting task with id $id")
        ...
      }
    }

Note

The methods supported by Logger are documented in the API at https://www.playframework.com/documentation/2.3.x/api/scala/index.html#play.api.Logger.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.221.144