"No log4j2 configuration file found." - scala

I've isolated this to a very simple test project that has no purpose other than simple log4j2test configuration + usage. The file directory structure:
.
├── build.sbt
└── src
└── main
├── resources
│ └── log4j2.xml
└── scala
└── mycompany
└── myapp
└── SimpleMain.scala
Build.sbt:
name := """log4j2test"""
version := "1.0.0-SNAPSHOT"
scalaVersion := "2.12.1"
scalacOptions := Seq("-unchecked", "-deprecation", "-encoding", "utf8")
libraryDependencies ++= {
Seq(
"org.apache.logging.log4j" % "log4j-slf4j-impl" % "2.8",
"org.apache.logging.log4j" % "log4j-api" % "2.8",
"org.apache.logging.log4j" % "log4j-core" % "2.8",
"com.fasterxml.jackson.dataformat" % "jackson-dataformat-yaml" % "2.8.6"
)
}
log4j2.xml contents are copy/pasted from example in official documentation: https://logging.apache.org/log4j/2.x/manual/configuration.html
SimpleMain.scala:
package mycompany.myapp
import org.slf4j.LoggerFactory
object SimpleMain {
val logger = LoggerFactory.getLogger(getClass())
def main(args: Array[String]): Unit = {
println("simple println test")
logger.info("this is a logger.info message")
logger.debug("this is a logger.debug message")
logger.error("this is a logger.error message")
val stream = this.getClass.getClassLoader.getResourceAsStream("log4j2.xml")
if (stream == null) {
println("failed to open log4j2.xml on classpath")
} else {
println("successfully opened log4j2.xml on classpath")
stream.close()
}
}
}
I run with
sbt "run-main mycompany.myapp.SimpleMain"
output:
[info] Running mycompany.myapp.SimpleMain
ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.
simple println test
14:12:14.508 [run-main-0] ERROR mycompany.myapp.SimpleMain$ - this is a logger.error message
successfully opened log4j2.xml on classpath
[success] Total time: 4 s, completed Feb 10, 2017 2:12:14 PM

Is it possible that the classloader for the SimpleMain application is different from the classloader for slf4j? Please try debugging the Log4j2 initialization by setting system property org.apache.logging.log4j.simplelog.StatusLogger.level to TRAC‌​E.

Is log4j2.xml being placed at the root of your jar? I am surprised getResourceAsStream is working. You have it specified as a relative path so it should be finding /mycompany/myapp/log4j2.xml.

Related

How to sbt publish multi module project

I'm a complete beginner in sbt/scala. I have a multi module sbt project that I build with sbt assembly, which creates jar files of my modules. When I tried sbt module2/publish I noticed the output jar file in my directory is super slim compared to the jar files created by sbt-assembly and its throwing error when I tried to run:
Error: Unable to initialize main class
com.example.module2.service.Server
Caused by: java.lang.NoClassDefFoundError: scala/Function0
What do I need to include in my build.sbt file to make sbt publishing possible?
my-proj
├── Build.scala
├── common
│   ├── build.sbt
│   └── src
├── module1
│   ├── build.sbt
│   └── src
├── module2
│   ├── build.sbt
│   └── src
└── project
├── build.properties
└── plugins.sbt
Build.scala
lazy val my_proj = (project in file("."))
.aggregate(common, module1, module2)
lazy val common = project
lazy val common = (project in file("commons"))
lazy val module1 = (project in file("module1"))
.dependsOn(common, module2)
lazy val module1 = (project in file("module1"))
.dependsOn(common)
module1/build.sbt
name := "module1"
version := "0.1"
organization := "com.example"
scalaVersion := "2.11.12"
val akkaVersion = "2.5.16"
scalacOptions ++= Seq("-unchecked", "-deprecation", "-Xcheckinit", "-encoding", "utf8")
fork := true
/** Dependencies */
resolvers ++= Seq("Akka Repository" at "http://repo.akka.io/releases/",
"Typesafe Repository" at "http://repo.typesafe.com/typesafe/releases/"
)
publishTo := Some(Resolver.file("file", new File("/tmp/my/artifactory")))
libraryDependencies ++= Seq(
"org.scala-lang" % "scala-library" % scalaVersion
, "org.scala-lang" % "scala-compiler" % scalaVersion
, "org.scala-lang" % "scala-reflect" % scalaVersion
, "com.typesafe.akka" %% "akka-actor" % akkaVersion
)
assemblyMergeStrategy in assembly := {
case "META-INF\\io.netty.versions.properties" => MergeStrategy.first
case m if m.toLowerCase.endsWith("manifest.mf") => MergeStrategy.discard
case m if m.toLowerCase.matches("meta-inf.*\\.sf$") => MergeStrategy.discard
case m if m.toLowerCase.startsWith("meta-inf/services/") => MergeStrategy.filterDistinctLines
case "reference.conf" => MergeStrategy.concat
case _ => MergeStrategy.first
}
To publish a "fat" jar to a repository, you have to add the following to build.sbt of each sub-project you want to publish.
Compile / assembly / artifact ~= { art =>
art.withClassifier(Some("fat"))
}
addArtifact(Compile / assembly / artifact, assembly).settings

Scala IDE: object scalatest is not a member of package org

I'm trying to use Scala IDE. I'm totally new to Scala.
HelloSpec.scala:
import org.scalatest._
class HelloSpec extends FlatSpec with Matchers {
"The Hello object" should "say hello" in {
Hello.greeting shouldEqual "hello"
}
}
import org.scalatest._ is marked by an error:
object scalatest is not a member of package org
I've tried to google it a lot but still don't understand what's wrong. My project structure looks right:
src/main/scala:
----Hello.scala
src/test/scala:
----HelloSpec.scala
build.sbt
plugins.sbt
build.sbt:
import Dependencies._
ThisBuild / scalaVersion := "2.12.8"
ThisBuild / version := "0.1.0-SNAPSHOT"
ThisBuild / organization := "com.example"
ThisBuild / organizationName := "example"
lazy val root = (project in file("."))
.settings(
name := "$name$",
libraryDependencies += scalaTest % Test
)
plugins.sbt:
addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "4.0.0")
I haven't build the project BTW. Is that could be the reason? I don't know how to build the project from Scala IDE, and if I build it from Windows Command Prompt then it doesn't influence Scala IDE.
I assume your project structure is as below,
src/
main/
resources/
<files to include in main jar here>
scala/
<main Scala sources>
test/
resources
<files to include in test jar here>
scala/
<test Scala sources>
build.sbt
plugins.sbt
This is simple hello class
object Hello {
def greeting: String = {
"hello"
}
}
I created the unit testing as below
import org.scalatest._
class HelloSpec extends FlatSpec with Matchers {
"The Hello object" should "say hello" in {
Hello.greeting shouldEqual "hello"
}
}
So, you need just to add scala test in dependcies. Below is simply sbt file
name := "Hello Test"
version := "0.1"
scalaVersion := "2.11.8"
libraryDependencies ++= Seq(
"org.scalatest" %% "scalatest" % "3.0.6" % "test")

ScalaPB not working when trying to compile SBT project. Compilation fails with "object gen is not a member of package scalapb"

I want to use the ScalaPB plugin in my SBT project. But when I try to compile the project I get an error that states the "object gen is not a member of package scalapb". So how do I configure this plugin to work with my project?
I followed the instructions on the Github page and it didn't work.
My project has the following structure, in other words the standard Maven project structure:
.
├── build.sbt
├── ci
│   └── checkstyle
├── LICENSE
├── project
│   ├── build.properties
│   ├── Dependencies.scala
│   ├── plugins.sbt
│   ├── project
│   └── target
├── src
│   ├── main
│   └── test
└── version.sbt
This is the Dependencies.scala file:
import sbt._
object Dependencies {
lazy val scalatestVersion = "3.0.5"
lazy val scalamockVersion = "4.1.0"
lazy val scalaPbcVersion = "0.8.3"
// Libraries for Protobuf
val scalaPbc = "com.thesamet.scalapb" %% "compilerplugin" % scalaPbcVersion
// Libraries for Testing
val scalatest = "org.scalatest" %% "scalatest" % scalatestVersion % Test
val scalamock = "org.scalamock" %% "scalamock" % scalamockVersion % Test
// Projects
val groupBackendDependencies = Seq(
scalatest, scalamock, scalaPbc)
}
This is the plugins.sbt file:
// The Typesafe repository
resolvers += "Typesafe repository" at "https://repo.typesafe.com/typesafe/maven-releases/"
// for autoplugins
addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "1.3.6" withSources())
dependencyOverrides += "com.puppycrawl.tools" % "checkstyle" % "8.12"
// Scala checkstyle
addSbtPlugin("org.scalastyle" %% "scalastyle-sbt-plugin" % "1.0.0")
// Scala Protobuf
addSbtPlugin("com.thesamet" % "sbt-protoc" % "0.99.19")
This is the build.sbt file. It is where the error occurs.
/** ****************************************************************************
* <REDACTED>
* ****************************************************************************
*/
enablePlugins(UniversalPlugin)
/** ****************************************************************************
* Application related configurations
* ****************************************************************************
*/
organization := "<REDACTED>"
name := "<REDACTED>"
packageName := "<REDACTED>"
/** ****************************************************************************
* Compilation related
* ****************************************************************************
*/
scalaVersion := "2.12.7"
scalacOptions ++= Seq("-target:jvm-1.8",
"-unchecked",
"-deprecation",
"-encoding", "utf8",
"-feature",
"-Ywarn-adapted-args",
"-Ywarn-dead-code")
javacOptions in(Compile, compile) ++= Seq("-source", "11",
"-target", "11",
"-g:lines")
logLevel := sbt.Level.Warn
exportJars := true
libraryDependencies ++= Dependencies.groupBackendDependencies
/** ****************************************************************************
* Packaging related configurations
* ****************************************************************************
*/
packageName in Universal := s"${packageName.value}-${version.value}"
exportJars := true
//By default, the dist task will include the API documentation in the generated package.
//Below instruction will exclude them/
sources in(Compile, doc) := Seq.empty
publishArtifact in(Compile, packageDoc) := false
/** ****************************************************************************
* CI : Scala Checkstyle
* Ref: http://www.scalastyle.org/sbt.html
* Usage: sbt scalastyle
* ****************************************************************************
*/
lazy val scalaCheckstyle = "ci/checkstyle/scala/scalastyle-config.xml"
scalastyleConfig := baseDirectory(_ / scalaCheckstyle).value
scalastyleFailOnWarning := true
/** ****************************************************************************
* CI : Pipeline Simulation
* Usage: sbt pipeline-ci
* ****************************************************************************
*/
commands += Command.command("pipeline-ci") { state =>
"clean" ::
"compile" ::
"test" ::
state
}
/**
* The error occurs here.
*/
PB.targets in Compile := Seq(
scalapb.gen() -> (sourceManaged in Compile).value
)
I expect that this project should compile with out any errors when running
sbt clean compile
But instead I get this stacktrace
/home/my-project/build.sbt:73: error: object gen is not a member of package scalapb
scalapb.gen() -> (sourceManaged in Compile).value
^
[error] Type error in expression
You are including ScalaPB's compiler plugin ("com.thesamet.scalapb" %% "compilerplugin" % scalaPbcVersion) as a library dependency of your project. The compiler plugin needs to be a dependency of your build project. To accomplish that, it needs to be add as a library dependency in your project/plugins.sbt.

Using Specs2 in a Typesafe activator play application

I have used specs2 many times successfully in vanilla SBT projects. now I am starting to learn typesafe activator platform.
I did the following steps
activator new Shop just-play-scala
this is my build.sbt file
name := """Shop"""
version := "1.0-SNAPSHOT"
// Read here for optional jars and dependencies
libraryDependencies ++= Seq("org.specs2" %% "specs2-core" % "3.6.1" % "test")
resolvers += "scalaz-bintray" at "http://dl.bintray.com/scalaz/releases"
scalacOptions in Test ++= Seq("-Yrangepos")
lazy val root = project.in(file(".")).enablePlugins(PlayScala)
I created a file Shop/app/test/models/ShopSpec.scala
import org.specs2.mutable.Specification
class ShopSpec extends Specification {
def foo = s2"""
| This is a specification to check the 'Hello world' string
| The 'Hello world' string should
| contain 11 characters $e1
| start with 'Hello' $e2
| end with 'world' $e3
| """.stripMargin
def e1 = "Hello world" must haveSize(11)
def e2 = "Hello world" must startWith("Hello")
def e3 = "Hello world" must endWith("world")
}
When I run activator test I get an error
[success] Total time: 0 s, completed Jun 24, 2015 12:21:32 AM
Mohitas-MBP:Shop abhi$ activator test
[info] Loading project definition from /Users/abhi/ScalaProjects/Shop/project
[info] Set current project to Shop (in build file:/Users/abhi/ScalaProjects/Shop/)
**cannot create a JUnit XML printer. Please check that specs2-junit.jar is on the classpath**
org.specs2.reporter.JUnitXmlPrinter$
java.net.URLClassLoader.findClass(URLClassLoader.java:381)
java.lang.ClassLoader.loadClass(ClassLoader.java:424)
sun.misc.Launcher$AppClassLoader.loadClass(Launcher.jav
I have previously written spec2 test cases successfully when I was using SBT projects. but only when I use the typesafe activator that I get this issue with test cases.
I even changed the code of my test to something as simple as
import org.specs2.mutable.Specification
class ShopSpec extends Specification {
"A shop " should {
"create item" in {
failure
}
}
}
But still the same problem.
Wait .. I think I resolved it.
The activator play platform already has specs2 included so there is no need for me to tweak the built.sbt file for specs 2.
So I removed everything I had added to build.sbt file and left the file as
name := """Shop"""
version := "1.0-SNAPSHOT"
lazy val root = project.in(file(".")).enablePlugins(PlayScala)
Now it works fine. So basically, I don't need to add anything in a activator project for specs2.
I could have deleted the question... but leaving it here so that it can be of help to someone.
What worked for me was adding the following to build.sbt:
libraryDependencies ++= Seq("org.specs2" %% "specs2-core" % "3.6.2" % "test",
"org.specs2" %% "specs2-junit" % "3.6.2" % "test")

ScalaTest on sbt not running any tests

I am trying to run my tests with:
sbt and then test.
My build.sbt looks like this
lazy val scalatest = "org.scalatest" % "scalatest_2.11" % "2.2.4" % "test"
lazy val root = (project in file(".")).
settings(
name := "highlight2pdf",
version := "0.1",
scalaVersion := "2.11.6",
libraryDependencies += scalatest
)
And i just put the example test on test/scala
import collection.mutable.Stack
import org.scalatest._
class ExampleSpec extends FlatSpec with Matchers {
"A Stack" should "pop values in last-in-first-out order" in {
val stack = new Stack[Int]
stack.push(1)
stack.push(2)
stack.pop() should be (2)
stack.pop() should be (1)
}
it should "throw NoSuchElementException if an empty stack is popped" in {
val emptyStack = new Stack[Int]
a [NoSuchElementException] should be thrownBy {
emptyStack.pop()
}
}
}
Still it always show:
[info] No tests were executed.
Any thoughts on why it's not working?
The directory structure isn't the correct convention for sbt to find ExampleSpec.scala by default.
├── built.sbt
├── src
│   └── test
│   └── scala
│   ├── ExampleSpec.scala
Change it to the structure above and run sbt test in the top level directory and it should work. Likewise, scala source would go in src/main/scala and would get compiled.
> test
[info] Compiling 1 Scala source to /tmp/TestsWontRun/target/scala-2.11/test-classes...
[info] ExampleSpec:
[info] A Stack
[info] - should pop values in last-in-first-out order
[info] - should throw NoSuchElementException if an empty stack is popped
[info] Run completed in 289 milliseconds.
[info] Total number of tests run: 2
[info] Suites: completed 1, aborted 0
[info] Tests: succeeded 2, failed 0, canceled 0, ignored 0, pending 0
[info] All tests passed.
[success] Total time: 7 s, completed Apr 30, 2015 8:54:30 AM