4

I would like to do some logging in SBT. I tried to get streams when initializing settingKey. However the compiler complains that A setting cannot depend on a task.

The config snippet is here.

val appConfig = settingKey[Config]("The parsed application.conf in SBT")

appConfig := {
  // ...
  streams.value.log.error("Cannot find application.conf. Please check if -Dconfig.file/resource is setting correctly.")
  // ...
}

Is there any method to do logging in settingKey? Thanks.

HKTonyLee
  • 3,111
  • 23
  • 34
  • Possible duplicate of [How to print to stream during sbt setting initialization](http://stackoverflow.com/questions/33765889/how-to-print-to-stream-during-sbt-setting-initialization) – Caoilte Jan 03 '17 at 22:02

3 Answers3

3

The proper way to log from an sbt setting is by using the Keys.sLog setting. This setting is set up by sbt and it holds the logger that it's used by other settings in the sbt universe.

val appConfig = settingKey[Config]("The parsed application.conf in SBT")

appConfig := {
  // ...
  Keys.sLog.value.log.error("Cannot find application.conf. Please check if -Dconfig.file/resource is setting correctly.")
  // ...
}
Jorge
  • 784
  • 4
  • 17
1

A setting should only hold settable data or something directly computable from other settings . streams is a task, so you can make another task depend on it and the appConfig setting. For example:

val appConfig = settingKey[File]("application.conf file")
val parsedAppConfig = taskKey[Config]("The parsed application.conf in SBT")

parsedAppConfig := {
  // ...
  parse(appConfig.value)
  // ...
  streams.value.log.error("Cannot find application.conf. Please check if -Dconfig.file/resource is setting correctly.")
  // ...
}
Justin Kaeser
  • 5,868
  • 27
  • 46
1

It's possible to go around streams and create a new ConsoleLogger() directly.

val appConfig = settingKey[Config]("The parsed application.conf in SBT")

appConfig := {
  // ...
  val logger: Logger = ConsoleLogger()
  logger.error("Cannot find application.conf. Please check if -Dconfig.file/resource is setting correctly.")
  // ...
}

Caveat: if streams.value.log gets set to something other than a ConsoleLogger, your log statement will be oblivious and still log to the console. That may be acceptable for your purposes though.

Doug Roper
  • 19
  • 1