Giter VIP home page Giter VIP logo

scala-logging's Introduction

Scala Logging is a convenient and fast logging library wrapping SLF4J.

It's convenient, because you can simply call log methods, without checking whether the respective log level is enabled:

logger.debug(s"Some $expensive message!")

It's fast, because thanks to Scala macros the check-enabled-idiom is applied and the following code is generated:

if (logger.isDebugEnabled) logger.debug(s"Some $expensive message!")

Prerequisites

  • Java 8 or higher
  • Scala 2.11, 2.12, 2.13 or 3.0
  • Logging backend compatible with SLF4J

A compatible logging backend is Logback, add it to your sbt build definition:

libraryDependencies += "ch.qos.logback" % "logback-classic" % "1.2.10"

If you are looking for a version compatible with Scala 2.10, check out Scala Logging 2.x.

Getting Scala Logging

Scala Logging is published to Sonatype OSS and Maven Central:

  • Group id / organization: com.typesafe.scala-logging
  • Artifact id / name: scala-logging

sbt users may add this to their build.sbt:

libraryDependencies += "com.typesafe.scala-logging" %% "scala-logging" % "3.9.4"

Using Scala Logging

The Logger class from the com.typesafe.scalalogging package wraps an underlying SLF4J logger. In order to create a Logger, you pass a name to the apply factory method defined in the Logger companion object:

val logger = Logger("name")

Or, you pass in a SLF4J logger instance:

val logger = Logger(LoggerFactory.getLogger("name"))

Or, you pass in the name of the class into which it is defined:

val logger = Logger(getClass.getName)

Or, you pass in a class:

val logger = Logger(classOf[MyClass])

Or, using the runtime class wrapped by the implicit class tag parameter:

val logger = Logger[MyClass]

The LazyLogging and StrictLogging traits from the com.typesafe.scalalogging package define the logger member as a lazy or strict value respectively, whereas the AnyLogging trait defines an abstract logger.

It depends on the individual use case which trait to use. However, we have defined some scenarios where you can use these traits:

  • Use LazyLogging if you are creating lots of objects with this trait repetitively.
  • Use StrictLogging pretty much by default, especially if the class is a singleton, or you know the log methods will always be invoked.
  • Use AnyLogging when writing some trait which needs access to any logger without deciding on a specific implementation.

In case of LazyLogging and StrictLogging, the underlying SLF4J logger is named according to the class into which these traits are mixed:

class LazyLoggingExample extends LazyLogging {
  logger.debug("This is Lazy Logging ;-)")

  logger.whenDebugEnabled {
    println("This would only execute when the debug level is enabled.")
    (1 to 10).foreach(x => println("Scala logging is great!"))
  }
}
class StrictLoggingExample extends StrictLogging {
  logger.debug("This is Strict Logging ;-)")

  logger.whenDebugEnabled {
    println("This would only execute when the debug level is enabled.")
    (1 to 10).foreach(x => println("Scala logging is great!"))
  }
}
class AnyLoggingExample extends AnyLogging {
  override protected val logger: Logger = Logger("name")

  logger.info("This is Any Logging ;-)")

  logger.whenInfoEnabled {
    println("This would only execute when the info level is enabled.")
    (1 to 10).foreach(x => println("Scala logging is great!"))
  }
}

LoggerTakingImplicit provides the same methods as Logger class, but with additional implicit parameter A. During creation of the LoggerTakingImplicit evidence CanLog[A] is required. It may be useful when contextual parameter (e.g. Correlation ID) is being passed around and you would like to include it in the log messages:

case class CorrelationId(value: String)
implicit case object CanLogCorrelationId extends CanLog[CorrelationId] {
  override def logMessage(originalMsg: String, a: CorrelationId): String = s"${a.value} $originalMsg"
}

implicit val correlationId = CorrelationId("ID")

val logger = Logger.takingImplicit[CorrelationId]("test")
logger.info("Test") // takes implicit correlationId and logs "ID Test"

If you want to extract the context object associated with your logger i.e. correlationId here, use getContext.

val context = logger.canLogEv.getContext()

It's also possible to use MDC through CanLog without any troubles with execution context.

case class CorrelationId(value: String)
implicit case object CanLogCorrelationId extends CanLog[CorrelationId] {
  override def logMessage(originalMsg: String, a: CorrelationId): String = {
    MDC.put("correlationId", a.value)
    originalMsg
  }

  override def afterLog(a: CorrelationId): Unit = {
    MDC.remove("correlationId")
  }
}

implicit val correlationId = CorrelationId("ID")

val logger = Logger.takingImplicit[CorrelationId]("test")

def serviceMethod(implicit correlationId: CorrelationId): Future[Result] = {
  dbCall.map { value =>
    logger.trace(s"Received value $value from db") // takes implicit correlationId
    toResult(value)
  }
}

String Interpolation

It is idiomatic to use Scala's string interpolation logger.error(s"log $value") instead of SLF4J string interpolation logger.error("log {}", value). However there are some tools (such as Sentry) that use the log message format as grouping key. Therefore they do not work well with Scala's string interpolation.

Scala Logging replaces simple string interpolations with their SLF4J counterparts like this:

logger.error(s"my log message: $arg1 $arg2 $arg3")
logger.error("my log message: {} {} {}", arg1, arg2, arg3)

This has no effect on behavior and performace should be comparable (depends on the underlying logging library).

Limitations

  • Works only when string interpolation is directly used inside the logging statement. That is when the log message is static (available at compile time).
  • Works only for the logger.<level>(message) and logger.<level>(marker, message) logging methods. It does not work if you want to log an exception and use string interpolation too (this is a limitation of the SLF4J API).

Line numbers in log message?

Using the sourcecode library, it's possible to add line number information (especially useful for debugging):

def foo(arg: String)(implicit line: sourcecode.Line, file: sourcecode.File) = {
  ... do something with arg ...
  ... do something with file.value ...
}

foo("hello") // the implicit sourcecode.File is filled in automatically

Maintenance status

This library is community-maintained. It is not supported under the Lightbend subscription.

Contribution policy

Contributions via GitHub pull requests are gladly accepted from their original author. Before we can accept pull requests, you will need to agree to the Lightbend Contributor License Agreement online, using your GitHub account.

scala-logging's People

Contributors

amumurst avatar analytically avatar atry avatar eugeniyk avatar francisdb avatar giabao avatar girishsubramanyam avatar hseeberger avatar jakubjanecek avatar jcracknell avatar jsw avatar justjoheinz avatar kpbochenek avatar kutchar avatar liff avatar marktickner avatar mentegy avatar mwielocha avatar ophirr33 avatar philippus avatar pjfanning avatar povder avatar prateekatknoldus avatar scala-steward avatar sethtisue avatar sorixelle avatar sullis avatar umhan35 avatar vagmcs avatar xuwei-k avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

scala-logging's Issues

LoggerSupport.class compiled with JDK8

Tried to use scalalogging in an android project using maven - with proguard being a part of the build.

the proguard phase of the build bails out with following message:

...
[INFO] java.io.IOException: Can't read [/Users/lad/.m2/repository/com/typesafe/scala-logging/scala-logging-slf4j_2.11/2.0.3/scala-logging-slf4j_2.11-2.0.3.jar(;;;;!META-INF/maven/**,!META-INF/MANIFEST.MF)] (Can't process class [com/typesafe/scalalogging/slf4j/LoggerSupport.class] (Unsupported class version number [52.0] (maximum 51.0, Java 1.7)))
...

It seems that LoggerSupport.class in the released 2.0.3 scala-logging-slf4j_2.11 was compiled with jdk8, but proguard doesn't understand jdk8 yet.

http://sourceforge.net/p/proguard/feature-requests/138/

i tried a workaround:

after compiling scalalogging myself with jdk1.6 and installing it locally in my repo i could get past the proguard step and could deploy my project with scala 2.11.0 with scalalogging on my android device.

Possible issue with Logging trait

I apologize in advance if I'm off base here, I know very (VERY) little about scala macros, and not much more about java's invoking of virtual (?) / overridden methods.

I ran into issues where a parent class/trait extended the Logging trait and then the concrete class defined the logger method (manually or using slf4j LazyLogging or StrictLogging). Any usage of that logger in the parent class seems to be calling com.typesafe.scalalogging.Logger's methods - which are "???" and throw a NotImplementedError, instead of calling the overridden macro method from the slf4j Logger.

I simplified this issue and replicated in the REPL:

scala> val logger = com.typesafe.scalalogging.slf4j.Logger(org.slf4j.LoggerFactory getLogger "test")
scala> (logger: com.typesafe.scalalogging.Logger) info "uheot"
scala.NotImplementedError: an implementation is missing
    at scala.Predef$.$qmark$qmark$qmark(Predef.scala:252)
    at com.typesafe.scalalogging.BaseLogger.info(Logger.scala:95)

Custom logger

In my project I want to have custom logger, based on scala-logging Logger class. But for now there is no possibility to create custom logger. Logger class is final and with private construstor.
I have tried some experiments in fork, but macroses makes all inheritance stuff very complicated.

Use scala-logging in a macro?

Hi,

I can't seem to control the log level when the logger is in a published macro.

My project is similar to this one, except that it's developed as a macro and test pair of sbt subprojects. I can control the log level as expected when testing locally, but after publishing, I can only control the log level of the loggers in the non-macro, and the macro's logger doesn't seem to see logback.xml.

Here's a minimized runnable example of a macro that will not be able to be silenced after publishing: macro-logging-example.

Are familiar with this issue and do you know of a fix?

If you wanted to add silenceable logging to the scala-logging macro, how would you do that?

Thanks,
Julian

Does not work with MDC

I have been looking through the code, but haven't been able to figure this out. I have some MDC values. If I use Play's built-in logging, which is also based on SLF4J and Logback, they appear in my logs. But with ScalaLogging, they do not.

ClassCastException with different scala version

Hi.

I'm using Vert.x to develop a module using Scala.

When I'm including scala-logging in the dependencies, it pulls in scala-reflect 2.11.1 whereas the scala-lang Vert.x module is using scala 2.11.2.

I suspect that this version mismatch between the scala-compiler and scala-reflect module causes the following exception:

java.lang.ClassCastException: 
  scala.tools.nsc.settings.MutableSettings$BooleanSetting cannot be cast to
  scala.reflect.internal.settings.MutableSettings$SettingValue

I guess that one needs to use the same version of scala-compiler and scala-reflect. Or am I just running into a classloader issue?

Iterable overwritten globally

Looks like java.lang.Iterable in is overwritten by com.typesafe.scalalogging.Iterable in the whole scope:

trait TClient {
  def submit(params: java.lang.Iterable[String]): Int
}

class Client() extends TClient {
  def submit(params: Iterable[String]): Int = 5
}

Generate an error like:

class Client needs to be abstract, since method submit in trait TClient of type (params: Iterable[String])Int is not defined
[error](Note that Iterable[String] does not match Iterable[String])

Request: Add Logger(class)

Add an apply method to Logger so that the user can do Logger(classOf[]) and not have to import and call org.slf4j.LoggerFactory.

Example: private val log = Logger(classOf[Dao])

[3.5.0] java.lang.NoClassDefFoundError: com/typesafe/scalalogging/Logger

My system information:

  • Scala: 2.11.8
  • SBT: 0.13.8

Import line in code file: import com.typesafe.scalalogging.Logger

Added these 2 lines in build.sbt file:

libraryDependencies += "ch.qos.logback" % "logback-classic" % "1.1.7"
libraryDependencies += "com.typesafe.scala-logging" %% "scala-logging" % "3.5.0"

Build successfully but when running jar file, I got this

Exception in thread "main" java.lang.NoClassDefFoundError: com/typesafe/scalalogging/Logger
        at java.lang.Class.getDeclaredMethods0(Native Method)
        at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
        at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
        at java.lang.Class.getMethod0(Class.java:3018)
        at java.lang.Class.getMethod(Class.java:1784)
        at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:720)
        at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:185)
        at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:210)
        at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:124)
        at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Caused by: java.lang.ClassNotFoundException: com.typesafe.scalalogging.Logger
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        ... 10 more

val logger = Logger(LoggerFactory.getLogger("name"))

As also described in http://stackoverflow.com/questions/42059088/scala-logging-instantiating-logger-named-defined-in-logback-xml

having logger defined in logback.xml,

I can not instantiate it by

val goalProgressLogger = Logger("goal-progress-logger")

or

val goalProgressLogger = LoggerFactory.getLogger("goal-progress-logger");

or
val goalProgressLogger = Logger(LoggerFactory.getLogger("goal-progress-logger"))

so that it would print output in desirable file

new version not source compatible

The package names have changed that means anything that uses this library (and there are many projects) now has to edit the source because of a change that's merely an implementation detail.

Can we please have the old package structure back?

I think if you alias LazyLogging or StrictLogging to Logging in this file: https://github.com/typesafehub/scala-logging/blob/master/scala-logging-slf4j/src/main/scala/com/typesafe/scalalogging/slf4j/Logging.scala

the balance will be restored and needless edits can be avoided. I would like to plead for source compatibility in a library as basic as logging.

Get InstantiationError

I've started getting this error:

java.lang.InstantiationError: Fatal execution error, caused by com.typesafe.scalalogging.Logger (Logger.scala:31)

I've tried this with 3.0.0, 3.1.0 and 3.2.0-SNAPSHOT. It consistently happens in one project that uses scala-logging but consistently does not happen in another project that uses exactly the same version of scala-logging. I've been scratching my head on this for a while now and thought I'd ask for help because it is not obvious to me how my compilation can yield the Logger class as being interpreted as an interface (trait).

I might be able to come up with a test case if that is needed, but first this is just an inquiry to see if someone else has run into this problem and knows how to fix it.

logger don't work

i get error when i try to use logger in/with sbt:

import org.slf4j.LoggerFactory
val logger = Logger(LoggerFactory.getLogger("name"))
logger.debug("This is very convenient ;-)")

error:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

[2.1.2] Add slf4j markers support

With 1.1.0 I have used log.error(marker, string). With 2.1.2 I get "ambiguous reference to overloaded definition". How to use markers with current version?

Ease parallel support of scala 2.10 and scala 2.11

We have a few generic libraries that we use across a variety of projects that makes extensive usage of scalalogging. As it turns out, we need to migrate to scala 2.11 in some projects while some others will stay behind for a few months.

I was able to support both scala versions with no code changes at all, except for scalalogging. I minimized these changes to one file where I simply hide the diverging import. This is how it looks:

with scala 2.10 (scalalogging):

package com.tarmath.utils.logging
import com.typesafe.scalalogging.slf4j.{Logging => ScalaLogging}
trait Logging extends ScalaLogging

with scala 2.11 (scala-logging):

package com.tarmath.utils.logging
import com.typesafe.scalalogging.{LazyLogging => ScalaLogging}
trait Logging extends ScalaLogging

However, this needs to be replicated into several other libraries, and complicates our builds quite a bit. We are thus hoping that perhaps this tiny interface could be added directly to scalalogging (the older package) so as to allow the exact same import as what the newer scala-logging library requires.

This could help other users of this library who are looking at upgrading and may need to support both versions for a while?

Otherwise, we'll proceed to add this hack everywhere and change our build processes.

Thanks!

Integrated scala trace debugging

Looks interesting: https://github.com/JohnReedLOL/scala-trace-debug

"Once upon a time, I had a very frustrating bug. It was caused by an idiosyncrasy in the semantics of a copy constructor that caused it to do a shallow copy instead of a deep copy and the code was multithreaded and required a deep copy.

This bug frustrated me because even though I looked at that very line of code from where the bug originated, I did not see the bug. It was so subtle.

How would I deal with such a subtle bug? I am not 100% sure how you would do it, but since I wrote this tool, let me explain to you how I would do it.

Do git bisect to find the commit that produced the bug.

Read the lines of code that were changed.

Put break points in the area of what was changed.

Follow this IntelliJ doc to enable hot reloading of source code while debugging. Scala IDE has similar "hot code replace" functionality.

Note: "Hot code replace adds the possibility to modify and re-compile (method body) code in a debug mode and to have these changes visible and taken into account by the debugged VM without restarting the application."

Hot code replace will cause your current stack frame to become obsolete and the JVM does not like obsolete frames. For hot code replace to work correctly, you must drop the obsolete frame by right clicking "Drop Frame" on the obsolete frame and then clicking "Step Over" (F8)."

Add OSGi manifest

Very useful library, it's really sad that it has no OSGi manifest

sample-swagger with scala-logging throws java.lang.IncompatibleClassChangeError: Implementing class

How to reproduce:
clone repository:
https://github.com/mhamrah/spray-swagger-sample

add in build.sbt:
"com.typesafe.scala-logging" %% "scala-logging" % "3.1.0",

then execute "sbt run"

Exception:
Uncaught error from thread [XXX.actor.default-dispatcher-5] shutting down JVM since 'akka.jvm-exit-on-fatal-error' is enabled for ActorSystem[XXX]
java.lang.IncompatibleClassChangeError: Implementing class
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:760)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:760)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)

Logger.info() cannot be used with primitive types

Hello,

import com.typesafe.scalalogging.StrictLogging

new StrictLogging { 
  logger.info("2 + 2 == {}", new Integer(4)) // compiles
  logger.info("2 + 2 == {}", 4)              // fails to compile
}

The error is:

overloaded method value info with alternatives:
  (marker: org.slf4j.Marker,message: String,args: AnyRef*)Unit <and>
  (marker: org.slf4j.Marker,message: String)Unit <and>
  (message: String,args: AnyRef*)Unit <and>
  (message: String,cause: Throwable)Unit
cannot be applied to (String, Int)

Is there any reason for using AnyRef* instead of Any* in:

class Logger {
  def info(message: String, args: AnyRef*): Unit = macro LoggerMacro.infoMessageArgs
}

If not, I can fix it and create a PR.

use Ivy revision ranges in Dependencies.scala

I get a warning from the scala-maven-plugin when building with your project, because the Scala version is different from the one I'm using:

[WARNING]  Expected all dependencies to require Scala version: 2.11.7
...
[WARNING]  com.typesafe.scala-logging.scala-logging_2.11:3.1.0 requires scala version 2.11.1
[WARNING] Multiple versions of scala libraries detected!

I'm guessing that this could be resolved, w/o any hackiness on my side, by setting the required revision in Dependencies.scala to [2.11,2.12[.

Disable logging at runtime

I would like to disable logging in some of my tests. What is the recommended way to achieve it? I am trying the following but logs are still present (please notice I am using Logback as logging backend):

import ch.qos.logback.classic.{Logger, Level}
import org.slf4j.LoggerFactory

val rootLogger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME).asInstanceOf[Logger]
rootLogger.setLevel(Level.OFF)

All my classes basically extend LazyLogging trait.

java.lang.InstantiationError: com.typesafe.scalalogging.Logger

Guys, I have odd problem that comes up once in a while and also magically disappears after I juggle with sbt clean comple, deleting target folder created by IDEA and restarting IntelliJ IDEA. Sometimes it takes me an hour to do these random actions which very very annoying.

I cannot find underlying cause.

What happens is I get following exception on start.

Exception in thread "main" java.lang.InstantiationError: com.typesafe.scalalogging.Logger
    at com.typesafe.scalalogging.Logger$.apply(Logger.scala:32)
    at com.typesafe.scalalogging.LazyLogging$class.logger(Logging.scala:28)
    at co.zzz.xxx.server.JournalsManager.logger$lzycompute(JournalsManager.scala:22)
    at co.zzz.xxx.server.JournalsManager.logger(JournalsManager.scala:22)
    at co.zzz.xxx.server.JournalsManager.<init>(JournalsManager.scala:42)
    at main$.main(main.scala:261)
    at main.main(main.scala)

where JournalsManager is object that extends com.typesafe.scalalogging.LazyLogging

In my build.scala I have following dependencies

          "com.typesafe.scala-logging" %% "scala-logging" % "3.5.0",
          "ch.qos.logback" % "logback-classic" % "1.1.+",

I'm on Scala 2.11.8

What should I do ?

Scala 2.10 version of the scala-logging not in Maven Central?

I couldn't find the logging library from Maven Central or Sonatype using the dependency specified in the README:

"com.typesafe.scala-logging" %% "scala-logging-slf4j" % "2.0.1"

Searching Maven Central returns only the Scala 2.11-RC versions of scala-logging. Is there a different place to look?

http://search.maven.org/#search%7Cga%7C1%7Ccom.typesafe%20logging

There is a scalalogging-slf4j for Scala 2.10, but the version only goes up to 1.1.0, not the 2.x released.

http://mvnrepository.com/artifact/com.typesafe/scalalogging-slf4j_2.10

Thanks.

Provide lazy log-if statements

I often have to write log statements that look like:

if (someCondition) logger.warn(s"Warning: $c")

The "someCondition" will be evaluated even if logging is disabled. Can you provide some way to do it more conveniently and efficiently?

Why macros?

in my experimenting the following yields the same result without the need for macros:

def debug(msg: => String) = if (loglevel >= Debug) println(msg) else ()

thus you can uses scalas built in string interpolation

logger.debug(s"Output is: ${expensiveFunc()}")

Examples of unit testing components that use Strict/LazyLogging

I have components where I want to unit test their logging side effects.

It would be good if the documentation demonstrated the recommended patterns for testing the logging of code that uses Strict/LazyLogging - apologies if I have missed this.

For now .. It would seem that the two traits require me to leave my classes non-final and override the method defined in the trait - is this the recommendation? Can you confirm if there is a more elegant approach and/or one where I can retain final classes.

Allow Access to is<LogLevel>Enabled methods?

Currently attempting to port my library to Scala 2.11.

I am thus moving from scalalogging to scala-logging... Whereas before I could call logger.underlying.isDebugEnabled, this is no longer possible with scala-logging.

Imagine the scenario where how much I want to log depends on the logging level:

logger.isDebugEnabled match {
case true => logger.debug(s"STATS $stat1 $stat2 $stat3 $stat4")
case false => logger.info(s"STATS $stat1")
}

Regardless of these methods being used behind the scene, it is still nice to access them depending on what exactly you want to do. Removing them from the exposed API removes some of the agility available to those who would employ slf4j directly for instance.

Of course, I could use multiple log lines here, but that would require quite a bit of adaptation elsewhere down our pipeline... :)

Thanks for your consideration!

InstantiationError when running from a fat jar

Code compiles and runs fine under sbt but i can't run it from a jar. Nothing changed in build.sbt, It always points the lines that contains "class .... extends LazyLogging". "object .... extends LazyLogging" seems fine , no problem with that.

Exception in thread "main" java.lang.InstantiationError: com.typesafe.scalalogging.Logger
at com.typesafe.scalalogging.Logger$.apply(Logger.scala:31)
at com.typesafe.scalalogging.LazyLogging$class.logger(Logging.scala:28)
at io.tazi.featureengineering.FeatureEngineering.logger$lzycompute(FeatureEngineering.scala:34)
at io.tazi.featureengineering.FeatureEngineering.logger(FeatureEngineering.scala:34)

wrong deps description

libraryDependencies += "com.typesafe.scala-logging" %% "scala-logging-slf4j" % "3.0.0"
don't work for me but:
libraryDependencies += "com.typesafe.scala-logging" %% "scala-logging" % "3.0.0"
does.

Compilation Error

I am unable to use the latest version. I get this error message:

Object LoggerSupport in package slf4j cannot be accessed in package com.typesafe.scalalogging.slf4j

I grepped my lib/ folder as well as my ~/.ivy2 folders for LoggerSupport and I am not finding any class named slf4j.LoggerSupport.

scala-logging-slf4j does not take into account call stack

scala-logging-slf4j does not take into account call stack,
so logback %class and %method do not work as expected:

  1. if logback.xml contains encoder pattern with 'class' and 'method':
%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %class{36} %method - %msg %n
  1. then LazyLogging with invocation
    logger.info("Invoked.")
    logger.info("Invoked. {}", "123")
  1. will produce
2014-06-23 11:08:17.136 [main-ScalaTest-running-MainSuite] INFO  boot.Main$ invoke - Invoked.
2014-06-23 11:08:17.136 [main-ScalaTest-running-MainSuite] INFO  c.t.scalalogging.slf4j.LoggerSupport info - Invoked. 123
  1. where line#1 is as expected, but line#2 reports wrong class and method.

macro to place logger in the companion

Having a val log in every instance is extremely expensive... more so for lazy vals.

It would be much more efficient if the val lived on the companion and the log were a def that delegated.

To pull this off, one would have to implement this as a macro or compiler plugin.

Until then, I see no real benefit of using this library over say, akka's Slf4jLogging trait, which already exists on most classpaths.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.