Last active
May 25, 2024 10:19
-
-
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/d35a81a1c8bf16ef08810e23ecca0c9640429648
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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.4.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