Last active
July 7, 2022 11:14
-
-
Save loverdos/25079d10636446f311adc0a57110d609 to your computer and use it in GitHub Desktop.
Logger with nested contexts
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
// Author: github.com/loverdos | |
// SPDX-License-Identifier: Apache-2.0 | |
import java.io.PrintStream | |
final class Logger(out: PrintStream = System.out) { | |
private var ctx = List[String]() | |
private val indent_chunk = " " | |
private def ctx_size = ctx.length | |
private def get_log_prefix( | |
indent: Int, | |
is_context: Boolean, | |
is_context_push: Boolean | |
): String = { | |
val sb = new StringBuilder | |
val indent_chunk_size: Int = indent_chunk.length | |
val max_n = indent * indent_chunk_size | |
for(n <- 0 to max_n) { | |
val s: String = | |
(n, is_context, is_context_push) match { | |
case (n, true, true) if n == max_n => ">" | |
case (n, true, true) if (n % indent_chunk_size) == 0 => "+" | |
case (_, true, true) => "-" | |
case (n, true, false) if n == max_n => "<" | |
case (n, true, false) if (n % indent_chunk_size) == 0 => "+" | |
case (_, true, false) => "-" | |
case (n, false, _) if (n % indent_chunk_size) == 0 => "|" | |
case (_, false, _) => " " | |
} | |
sb.append(s) | |
} | |
sb.toString() | |
} | |
private def println_raw(s: String): Unit = out.println(s) | |
def push_ctx(name: String, info: String = ""): Unit = { | |
ctx = name :: ctx | |
val prefix = get_log_prefix(ctx_size, true, true) | |
//val msg = prefix + " (" + name + ")" | |
val msg = prefix + " " + name | |
println_raw(msg) | |
if(info.nonEmpty) { | |
log(">> " + info) | |
} | |
} | |
def pop_ctx(info: String = ""): Unit = { | |
val name = ctx.head | |
val prefix = get_log_prefix(ctx_size, true, false) | |
//val msg = prefix + " (" + name + ")" | |
val msg = prefix + " " + name | |
if(info.nonEmpty) { | |
log("<< " + info) | |
} | |
println_raw(msg) | |
ctx = ctx.tail | |
} | |
def log(ss: String*): Unit = { | |
val prefix = get_log_prefix(ctx_size, false, false) | |
val s = ss.mkString("") | |
println_raw(prefix + " " + s) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment