Saturday, August 9, 2014

update: Scala Spring 4 MVC without Web.XML - logging with Log4j and SLF4j

  This is small update to the previous blogpost (Scala Spring 4 MVC without Web.XML). It shows how to add commonly used Java libraries into the Spring scala project. 
In this example is log4j 1.x used but any change can be easily done when you clone my git hub project. Basically this post shows how to add commonly used libraries into any scala project.

  Let's import last version of Simple Logging Facede 4 Java (SLF4J) and not thin Scala (SLF4S) wrapper to it which is written by Heiko Seeberger.

  We do whole example update in several steps:
1. we need to update our build.sbt file and import appropriate library dependencies
libraryDependencies ++= Seq(
  "org.springframework" % "spring-webmvc" % "4.0.6.RELEASE",
  "org.springframework" % "spring-context" % "4.0.6.RELEASE",
  "org.springframework" % "spring-context-support" % "4.0.6.RELEASE",
  "javax.servlet" % "javax.servlet-api" % "3.0.1" % "provided",
  "javax.servlet" % "jstl" % "1.2" % "compile",
  "org.slf4j" % "jcl-over-slf4j" % "1.7.5" ,
  "org.slf4j" % "slf4j-api" % "1.7.5" ,
  "org.slf4j" % "slf4j-log4j12" % "1.7.5",
  "log4j" % "log4j" % "1.2.17" excludeAll(
        ExclusionRule(organization = "com.sun.jdmk"),
        ExclusionRule(organization = "com.sun.jmx"),
        ExclusionRule(organization = "javax.jms")
  "org.eclipse.jetty" % "jetty-webapp" % "9.1.0.v20131115" % "container, compile",
  "org.eclipse.jetty" % "jetty-jsp" % "9.1.0.v20131115" % "container"

2. in the resources folder we configure log4j logger and some properties (Img.1.). Example configuration is done for Tomcat server.
Img.1.:: Spring 4 Scala project structure with logging configuration
 3. org.slf4j.LoggerFactory is now available for import into HelloExampleController and to log Controller behaviour.
private val logger = LoggerFactory.getLogger(getClass)

@RequestMapping(method =  Array(RequestMethod.GET))
def hello( model: Model) = {"Info Test")
  logger.debug("Debug Test")
  logger.error("Error Test")

All code is available over my github for testing. Small hint could be Log4j 2 which promises significant improvements over its predecessor, logback and etc.

No comments: