Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 7, 2023 16:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacr/b1058e8e2d9febd9495844b14ea04d5e to your computer and use it in GitHub Desktop.
Save dacr/b1058e8e2d9febd9495844b14ea04d5e to your computer and use it in GitHub Desktop.
Experimenting scala logging approach. / published by https://github.com/dacr/code-examples-manager #db278342-7a77-4013-9609-b74ad5a4f8e0/8c3c507a38b3f72c347de4421a975f574a489234
// summary : Experimenting scala logging approach.
// keywords : scala, logs, experiment
// publish : gist
// authors : David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : db278342-7a77-4013-9609-b74ad5a4f8e0
// created-on : 2020-05-31T19:54:52Z
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// ---------------------
//> using scala "3.2.2"
// ---------------------
def now() = System.currentTimeMillis
case class LogContext(tuples: Map[LogContext.TagKey, LogContext.TagValue])
object LogContext {
type TagKey = Symbol
type TagValue = String
type TagTuple = Tuple2[TagKey, TagValue]
def apply(tuples: TagTuple*): LogContext = LogContext(tuples.toMap)
implicit def tuplesArray2LogContext(tuples: Array[LogContext.TagTuple]): LogContext = LogContext(tuples.toMap)
}
def log(msg: String)(implicit ctx: LogContext) = println(msg + " " + ctx.tuples.toString)
def logprov[T](proc: ((String) => Any) => T)(implicit ctx: LogContext): T = proc(log(_))
def logaround[T](what: String)(proc: => T)(implicit ctx: LogContext): T = {
log(s"$what starts")
val result = proc
log(s"$what ends")
result
}
def logperf[T](msg: String)(proc: => T)(implicit ctx: LogContext): T = {
val started = now()
val result = proc
val ended = now() - started
log(s"$msg")(new LogContext(ctx.tuples + (Symbol("duration") -> ended.toString)))
result
}
// ---------------------------------------------------------------------
implicit val ctx: LogContext = LogContext(Symbol("pid") -> "32", Symbol("client") -> "toto", Symbol("logger") -> "dummy")
log("1.coucou")
logprov { logger =>
// some initialization
logger("2.ready")
// some processing
logger("2.do it")
// some other thing
}
logperf("3.howmuchtime") {
// some synchronous potentially long processing
Thread.sleep(200)
}
logaround("4.complex processing") {
// do some very complex processing
1 + 1
}
/*
val eventualFuture = Future(1+1)
logfut("5.some future result")(eventualFuture)
.map(
// TO BE CONTINUED...
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment