From 2ec6d4f9c57d5b2af99a9f2a990a428c02de4c9b Mon Sep 17 00:00:00 2001 From: Gregor Heine Date: Fri, 17 Jan 2025 20:06:10 +0100 Subject: [PATCH] FDN-2469: Add default logger for use outside play framework --- .../scala/io/flow/log/RollbarLogger.scala | 29 ++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/src/main/scala/io/flow/log/RollbarLogger.scala b/src/main/scala/io/flow/log/RollbarLogger.scala index 58fec9c..c85d1e0 100644 --- a/src/main/scala/io/flow/log/RollbarLogger.scala +++ b/src/main/scala/io/flow/log/RollbarLogger.scala @@ -3,12 +3,14 @@ package io.flow.log import cats.data.NonEmptyChain import com.google.inject.assistedinject.{Assisted, AssistedInject} import com.rollbar.notifier.Rollbar +import io.flow.util.FlowEnvironment import net.logstash.logback.marker.Markers.appendEntries import org.slf4j.LoggerFactory import play.api.libs.json.{JsValue, Json, Writes} import scala.jdk.CollectionConverters._ -import scala.util.Random +import scala.util.control.NonFatal +import scala.util.{Random, Try} object RollbarLogger { @@ -17,6 +19,31 @@ object RollbarLogger { val SimpleLogger: RollbarLogger = RollbarLogger(rollbar = None, attributes = Map.empty, legacyMessage = None, shouldSendToRollbar = false) + private def rollbarToken(): String = { + sys.env + .get("ROLLBAR_TOKEN") + .getOrElse { + sys.error("missing env variable: ROLLBAR_TOKEN") + } + } + + lazy val Default: RollbarLogger = { + if (FlowEnvironment.Current == FlowEnvironment.Production) { + Try { + val rollbar = RollbarProvider.rollbar(rollbarToken()) + RollbarLogger.SimpleLogger.copy( + rollbar = Some(rollbar), + shouldSendToRollbar = true + ) + }.recover { case NonFatal(e) => + Console.err.println(s"WARN Failed to load Rollbar logger, using simple logger: $e") + RollbarLogger.SimpleLogger + }.get + } else { + RollbarLogger.SimpleLogger + } + } + trait Factory { @AssistedInject def rollbar(