59 lines
2.0 KiB
Kotlin
59 lines
2.0 KiB
Kotlin
package Log
|
|
|
|
import org.tinylog.Logger
|
|
import java.nio.file.Files
|
|
import java.nio.file.Paths
|
|
|
|
/**
|
|
* Class to get log data from log files
|
|
*/
|
|
@Suppress("UNUSED")
|
|
class LogGetter {
|
|
// valid date format either dd-MM-yyyy or dd/MM/yyyy
|
|
private val dateRegex = """(\d{2})[-/](\d{2})[-/](\d{4})""".toRegex()
|
|
// each logline is in format dd/MM/yyyy HH:mm:ss Function: Message
|
|
private val logLineRegex = """(\d{2}/\d{2}/\d{4}) (\d{2}:\d{2}:\d{2}) (.+?): (.+)""".toRegex()
|
|
// log folder is current working directory + /logs
|
|
private val logFolder: String = System.getProperty("user.dir") + "/logs"
|
|
|
|
/**
|
|
* Get log data for a specific date
|
|
* @param date Date in format dd-MM-yyyy or dd/MM/yyyy
|
|
* @return List of LogData for the specified date or empty list if date is invalid or no logs found
|
|
*/
|
|
fun getLog(date: String) : ArrayList<LogData> {
|
|
// check date with dateRegex and find dd MM yyyy
|
|
val x = dateRegex.find(date)
|
|
if (x==null) {
|
|
Logger.error { "Invalid date format: $date" }
|
|
return arrayListOf()
|
|
}
|
|
val (day, month, year) = x.destructured
|
|
|
|
|
|
// logFilePath is logFolder/year/month/day.log
|
|
val p = Paths.get(logFolder, year, month, "${day}.log")
|
|
// check if file exists
|
|
if (!Files.exists(p)) {
|
|
Logger.error { "Log file does not exist: $p" }
|
|
return arrayListOf()
|
|
}
|
|
val logDataList = ArrayList<LogData>()
|
|
Files.newBufferedReader(p).useLines { lines ->
|
|
lines.forEachIndexed { index, string ->
|
|
val ll = logLineRegex.find(string)
|
|
if (ll != null && ll.groupValues.size == 5) {
|
|
val logData = LogData(
|
|
index ,
|
|
ll.groupValues[1],
|
|
ll.groupValues[2],
|
|
ll.groupValues[3],
|
|
ll.groupValues[4]
|
|
)
|
|
logDataList.add(logData)
|
|
}
|
|
}
|
|
}
|
|
return logDataList
|
|
}
|
|
} |