otakusenpai
10/19/2018, 3:22 AMclass AsyncLogger : AbstractLogger {
constructor(filepath: String,name: String) : super() {
var file = File(filepath)
file.mkdirs()
filename = "$filepath/$name"
file = File(filename)
}
suspend fun log(toLog: Boolean,msg: String) = coroutineScope {
GlobalScope.launch {
if (toLog)
writeToFile(msg)
}
}
suspend fun log(toLog: Boolean,toFile: Boolean,msg: String) = coroutineScope {
GlobalScope.launch {
if(toLog)
when(toFile) {
true -> writeToFile(msg)
false -> writeToFile(msg)
}
}
}
override suspend fun writeToSTDOUT(msg: String) =
println(message = "[${Thread.currentThread().name}]: $msg")
override suspend fun writeToFile(msg: String): Job = coroutineScope {
GlobalScope.launch {
val stream = RandomAccessFile(filename, "rw")
val channel = stream.channel
var lock: FileLock? = null
try {
lock = channel.tryLock()
} catch (e: OverlappingFileLockException) {
stream.close()
channel.close()
}
stream.writeBytes(msg + '\n')
lock?.release()
stream.close()
channel.close()
}
}
}
Exception in thread "DefaultDispatcher-worker-2" java.io.IOException: Stream Closed
at java.io.RandomAccessFile.writeBytes(Native Method)
at java.io.RandomAccessFile.writeBytes(RandomAccessFile.java:1100)
at com.github.otakusenpai.aghora.commonUtils.log.AsyncLogger$writeToFile$2$1.doResume(AsyncLogger.kt:50)
at kotlin.coroutines.experimental.jvm.internal.CoroutineImpl.resume(CoroutineImpl.kt:54)
at kotlinx.coroutines.experimental.DispatchedTask$DefaultImpls.run(Dispatched.kt:168)
at kotlinx.coroutines.experimental.DispatchedContinuation.run(Dispatched.kt:13)
at kotlinx.coroutines.experimental.scheduling.Task.run(Tasks.kt:94)
at kotlinx.coroutines.experimental.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:583)
at kotlinx.coroutines.experimental.scheduling.CoroutineScheduler.access$runSafely(CoroutineScheduler.kt:60)
at kotlinx.coroutines.experimental.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:729)
stream.close()
Nikky
10/19/2018, 3:24 AMotakusenpai
10/19/2018, 3:25 AMNikky
10/19/2018, 3:26 AMotakusenpai
10/19/2018, 3:26 AMhallvard
10/19/2018, 6:11 AMuse {}
you don't have to bother about closing the streams yourself ...otakusenpai
10/19/2018, 6:11 AMAlexander
10/22/2018, 2:06 PMoverride suspend fun writeToFile(msg: String) = scope.actor<String> {
for (msg in this) {
stream.writeBytes("$msg\n")
}
}
log
function you can just send message into the channel.log
function:
suspend fun log(msg: String, toLog: Boolean, toFile: Boolean = false)
Possibly it is worth to combine toLog
& toFile
arguments into an enum.scope
can be passed via constructor, so you will be able to define the scope from the outside.