Question

def buildLog(appName: String) = {
  val file = s"${sys.env("HOME")}/builds/logs/${appName}.log"
  val f = new File(file)
  Enumerator.fromFile(f).map(new String(_))
}

I want to display a rolling log file to the web page, I use Enumerator.fromFile() method and map the byte array to String, but I am getting some strange chars like

From xxx:yyy/zzz
 * branch            master     -> FETCH_HEAD
Already up-to-date.
[0m[[0minfo[0m] [0mLoading project definition from /home/zzz/builds/sources/ops-ui/project[0m
[0m[[0minfo[0m] [0mSet current project to zzz (in build file:/home/zzz/builds/sources/ops-ui/)[0m
[0m[[32msuccess[0m] [0mTotal time: 0 s, completed 2013-12-30 17:38:53[0m

How to display the content correctly?

Was it helpful?

Solution

Those characters define colors the console should use to display the text (e.g. info in cyan and errors in red).

To remove the characters from your file, you can change the logging configuration, for example replace %coloredLevel with %level in conf/logger.xml.

Alternatively, you could implement a custom LogManager to rewrite logs as needed. This is inspired by similar emojiLogs, but I did not test it:

logManager ~= { lm =>
  new LogManager {
    def apply(
        data: sbt.Settings[Scope],
        state: State,
        task: Def.ScopedKey[_],
        writer: java.io.PrintWriter
    ) = {
      val l = lm.apply(data, state, task, writer)
      new Logger {
        val Escapes = Set("M\\\\[2K", "\\[0m", "\\[32m")
        def ommitColorChars(str: String) = Escapes.fold(str)(_.replaceAll(_))
        def log(level: Level.Value, message: => String) =
          l.log(level, ommitColorChars(message))
        def success(message: => String) = l.success(message)
        def trace(t: => Throwable) = l.trace(t)
        override def ansiCodesSupported = l.ansiCodesSupported
      }
    }
  }
}

OTHER TIPS

Just to complete a bit more the answer, I found a more general way of removing coloured logs. The colouring characters can be removed as (assuming you have a string with the coloured logs):

string.replaceAll("""\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]""", "")

Inspired by the equivalent "sed" in Linux command (1):

sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top