Skip to content

Instantly share code, notes, and snippets.

@notxcain
Created June 7, 2018 14:12
Show Gist options
  • Save notxcain/4969a85219decf1e86986946b3f0a5c5 to your computer and use it in GitHub Desktop.
Save notxcain/4969a85219decf1e86986946b3f0a5c5 to your computer and use it in GitHub Desktop.
Logger[F[_]]
import cats.Applicative
import cats.effect.Sync
import com.evotor.common.logging.Logger.Level
import org.slf4j.LoggerFactory
import scala.reflect.ClassTag
trait Logger[F[_]] {
def log(level: Level.Value, msg: => String, throwable: Throwable): F[Unit]
@inline final def trace(msg: => String, thrown: Throwable = null): F[Unit] =
log(Level.Trace, msg, thrown)
@inline final def debug(msg: => String, thrown: Throwable = null): F[Unit] =
log(Level.Debug, msg, thrown)
@inline final def info(msg: => String, thrown: Throwable = null): F[Unit] =
log(Level.Info, msg, thrown)
@inline final def warn(msg: => String, thrown: Throwable = null): F[Unit] =
log(Level.Warn, msg, thrown)
@inline final def error(msg: => String, thrown: Throwable = null): F[Unit] =
log(Level.Error, msg, thrown)
}
object Logger {
object Level extends Enumeration {
val Trace, Debug, Info, Warn, Error = Value
}
object slf4j {
def apply[F[_]: Sync, T: ClassTag]: Logger[F] =
slf4j(LoggerFactory.getLogger(implicitly[ClassTag[T]].runtimeClass))
def apply[F[_]: Sync](name: String): Logger[F] =
slf4j(LoggerFactory.getLogger(name))
def apply[F[_]](logger: org.slf4j.Logger)(implicit F: Sync[F]): Logger[F] =
new Logger[F] {
final override def log(level: Level.Value,
msg: => String,
throwable: Throwable): F[Unit] =
F.delay {
level match {
case Level.Trace if logger.isTraceEnabled() =>
logger.trace(msg, throwable)
case Level.Debug if logger.isDebugEnabled() =>
logger.debug(msg, throwable)
case Level.Info if logger.isInfoEnabled() =>
logger.info(msg, throwable)
case Level.Warn if logger.isWarnEnabled() =>
logger.warn(msg, throwable)
case Level.Error if logger.isErrorEnabled() =>
logger.error(msg, throwable)
case _ => ()
}
}
}
}
def noop[F[_]](implicit F: Applicative[F]): Logger[F] = new Logger[F] {
override def log(level: Level.Value,
msg: => String,
throwable: Throwable): F[Unit] =
F.pure(())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment