Log session to ~/.ijp_imagej_launcher.log #6

This commit is contained in:
Jarek Sacha 2023-06-07 20:25:56 -04:00
parent ce0c49c515
commit 11b248fc1f
No known key found for this signature in database
GPG key ID: F29625CE62288163
2 changed files with 46 additions and 1 deletions

5
notes/v.0.2.0.md Normal file
View file

@ -0,0 +1,5 @@
### New Features
* Use launcher location to infer `ij-dir`. #5
* Session log is saved to `~/.ijp_imagej_launcher.log` to facilitate troubleshooting when not running from command
prompt. The log is reset for each session. #6

View file

@ -5,20 +5,60 @@
package ij_plugins.imagej_launcher package ij_plugins.imagej_launcher
import ij_plugins.imagej_launcher.Logger.Level import ij_plugins.imagej_launcher.Logger.{Level, logToFile}
import os.Path
import java.nio.file.{Files, StandardOpenOption}
import scala.util.control.NonFatal
class Logger(val level: Level = Level.Info): class Logger(val level: Level = Level.Info):
def debug(msg: String): Unit = pprint(Level.Debug, msg) def debug(msg: String): Unit = pprint(Level.Debug, msg)
def info(msg: String): Unit = pprint(Level.Info, msg) def info(msg: String): Unit = pprint(Level.Info, msg)
def error(msg: String): Unit = pprint(Level.Error, msg) def error(msg: String): Unit = pprint(Level.Error, msg)
private def pprint(l: Level, message: String): Unit = private def pprint(l: Level, message: String): Unit =
val m = f"${l.name}%-5s: $message"
if l.level <= level.level then println(f"${l.name}%-5s: $message") if l.level <= level.level then println(f"${l.name}%-5s: $message")
logToFile(m)
object Logger: object Logger:
private val LogFile: Path = os.home / ".ijp_imagej_launcher.log"
private var logFileReset: Boolean = true
enum Level(val level: Int, val name: String): enum Level(val level: Int, val name: String):
case Off extends Level(0, "OFF") case Off extends Level(0, "OFF")
case Error extends Level(200, "ERROR") case Error extends Level(200, "ERROR")
case Info extends Level(400, "INFO") case Info extends Level(400, "INFO")
case Debug extends Level(500, "DEBUG") case Debug extends Level(500, "DEBUG")
case All extends Level(Int.MaxValue, "DEBUG") case All extends Level(Int.MaxValue, "DEBUG")
private def logToFile(message: String): Unit =
try
if logFileReset && os.exists(LogFile) then
val _ = os.remove(LogFile)
logFileReset = false
val data = readableTimeStamp() + ": " + message + "\n"
val lines = data.getBytes()
val _ = Files.write(
LogFile.toNIO,
lines,
StandardOpenOption.CREATE,
StandardOpenOption.APPEND,
StandardOpenOption.WRITE
)
catch
case NonFatal(_) =>
// Ignore exceptions
private def readableTimeStamp(): String =
// Simple implementation returns GMT time (no date)
// Use custom code as DateTimeFormatter is not available in Scala Native 0.4.14
val t = System.currentTimeMillis()
val sss = t % 1000
val ss = (t / 1000L).toInt % 60
val mm = (t / (1000L * 60L)).toInt % 60
val hh = (t / (1000L * 60L * 60L)).toInt % 24
f"$hh%02d-$mm%02d-$ss%02d_$sss%03dZ"