加入日志系统

This commit is contained in:
guigui
2022-05-29 23:58:20 +08:00
parent b7c52ccbbe
commit eb5c556b09
6 changed files with 142 additions and 79 deletions

View File

@@ -30,6 +30,8 @@ dependencies {
implementation("io.ktor:ktor-server-cors:$ktor_version")
implementation("io.ktor:ktor-server-websockets:$ktor_version")
implementation("ch.qos.logback:logback-classic:$logback_version")
implementation("io.ktor:ktor-server-call-logging:$ktor_version")
implementation("io.ktor:ktor-server-double-receive:$ktor_version")
testImplementation("io.ktor:ktor-server-tests-jvm:$ktor_version")
testImplementation("org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.3")

View File

@@ -2,13 +2,22 @@ package com.iguigui.maaj
import com.iguigui.maaj.routing.httpRouting
import com.iguigui.maaj.routing.wsRouting
import io.ktor.http.*
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.netty.*
import io.ktor.server.application.*
import io.ktor.server.plugins.callloging.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.plugins.cors.routing.*
import io.ktor.server.plugins.doublereceive.*
import io.ktor.server.request.*
import io.ktor.server.websocket.*
import io.ktor.util.logging.*
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
import org.slf4j.event.Level
fun main(args: Array<String>): Unit = EngineMain.main(args)
@@ -18,7 +27,12 @@ fun Application.module() {
wsRouting()
}
fun Application.configure(){
lateinit var logger : Logger
fun Application.configure() {
logger = log
//Input and output serialize
install(ContentNegotiation) {
json(Json {
encodeDefaults = true
@@ -39,4 +53,28 @@ fun Application.configure(){
maxFrameSize = Long.MAX_VALUE
masking = false
}
//Provides the ability to receive a request body several times.
install(DoubleReceive) {
}
//Logging request body.
install(CallLogging) {
level = Level.INFO
format { call ->
val status = call.response.status()
val httpMethod = call.request.httpMethod
val queryParameters = call.request.rawQueryParameters
when (httpMethod) {
HttpMethod.Get -> "Status: $status, HTTP method: $httpMethod, Uri: ${call.request.uri}, QueryParameters: $queryParameters "
HttpMethod.Post -> runBlocking {
"Status: $status, HTTP method: $httpMethod, Uri: ${call.request.uri} ,Body: ${
call.receive<JsonElement>().toString()
} "
}
else -> {
"Status: $status, HTTP method: $httpMethod, Uri: ${call.request.uri}, QueryParameters: $queryParameters "
}
}
}
}
}

View File

@@ -1,6 +1,7 @@
package com.iguigui.maaj.routing
import com.iguigui.maaj.dto.*
import com.iguigui.maaj.logger
import com.iguigui.maaj.service.Connection
import com.iguigui.maaj.service.MaaService
import com.iguigui.maaj.service.MaaService.addConnection
@@ -20,13 +21,14 @@ import kotlin.collections.LinkedHashSet
fun Application.wsRouting() {
routing {
webSocket("/API/V1") {
println("Adding user!")
val connection = Connection(this)
logger.info("Ws connection connected ! connection : ${connection.session} ")
addConnection(connection)
try {
for (frame in incoming) {
frame as? Frame.Text ?: continue
val receivedText = frame.readText()
logger.info(receivedText)
val wsRequest = Json.decodeFromString(WsRequest.serializer(), receivedText)
var response: BaseData? = null
when (wsRequest.command) {
@@ -86,10 +88,10 @@ fun Application.wsRouting() {
}
} catch (e: Exception) {
e.printStackTrace()
println(e.message)
logger.warn("Ws Exception $e.message")
logger.warn(e.stackTraceToString())
} finally {
println("Removing $connection!")
logger.info("Ws connection disconnected ! connection : $connection ")
removeConnection(connection)
}
}

View File

@@ -3,8 +3,10 @@ package com.iguigui.maaj.service
import com.iguigui.maaj.dto.CallBackLog
import com.iguigui.maaj.dto.*
import com.iguigui.maaj.easySample.MeoAssistant
import com.iguigui.maaj.logger
import com.iguigui.maaj.util.Json
import com.sun.jna.Pointer
import io.ktor.server.application.*
import java.util.concurrent.atomic.AtomicLong
import kotlin.reflect.KFunction1
@@ -48,9 +50,9 @@ class MaaInstance(
override fun callback(msg: Int, detail_json: String, custom_arg: String) {
System.out.printf("回调msg : %s , 回调 detail_json : %s ,回调 custom_arg : %s \n", msg, detail_json, custom_arg)
val callBackLog = CallBackLog(id, msgId.getAndIncrement(), msg, Json.parseToJsonElement(detail_json))
callBackAction?.call(callBackLog)
logger.info("callBackLog = $callBackLog")
callBackAction.call(callBackLog)
when (msg) {
INTERNAL_ERROR,
INIT_FAILED,

View File

@@ -8,4 +8,25 @@
<appender-ref ref="STDOUT"/>
</root>
<logger name="io.netty" level="INFO"/>
<appender name="ROLLING" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>log/maa-http.log </file>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<!-- rollover daily -->
<fileNamePattern>maa-http-%d{yyyy-MM-dd}.%i.txt</fileNamePattern>
<!-- each file should be at most 100MB, keep 60 days worth of history, but at most 20GB -->
<maxFileSize>10MB</maxFileSize>
<maxHistory>10</maxHistory>
<totalSizeCap>100MB</totalSizeCap>
</rollingPolicy>
<append>true</append>
<encoder>
<pattern>%d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="info">
<appender-ref ref="ROLLING"/>
</root>
</configuration>

View File

@@ -20,78 +20,76 @@ class HttpRoutingKtTest {
}
client.get("/API/V1/getVersion").apply {
Assert.assertEquals(status,OK)
val body :GetVersionResponse = body()
println(body.version)
}
}
@Test
fun testPostApiV1Connect() = testApplication {
application {
httpRouting()
}
client.post("/API/V1/connect").apply {
}
}
@Test
fun testPostApiV1Appendtask() = testApplication {
application {
httpRouting()
}
client.post("/API/V1/appendTask").apply {
TODO("Please write your test here")
}
}
@Test
fun testPostApiV1Settaskparams() = testApplication {
application {
httpRouting()
}
client.post("/API/V1/setTaskParams").apply {
TODO("Please write your test here")
}
}
@Test
fun testPostApiV1Start() = testApplication {
application {
httpRouting()
}
client.post("/API/V1/start").apply {
TODO("Please write your test here")
}
}
@Test
fun testPostApiV1Stop() = testApplication {
application {
httpRouting()
}
client.post("/API/V1/stop").apply {
TODO("Please write your test here")
}
}
@Test
fun testPostApiV1Destroy() = testApplication {
application {
httpRouting()
}
client.post("/API/V1/destroy").apply {
TODO("Please write your test here")
}
}
@Test
fun testGetApiV1Listinstance() = testApplication {
application {
httpRouting()
}
client.get("/API/V1/listInstance").apply {
TODO("Please write your test here")
}
}
//
// @Test
// fun testPostApiV1Connect() = testApplication {
// application {
// httpRouting()
// }
// client.post("/API/V1/connect").apply {
//
// }
// }
//
// @Test
// fun testPostApiV1Appendtask() = testApplication {
// application {
// httpRouting()
// }
// client.post("/API/V1/appendTask").apply {
// TODO("Please write your test here")
// }
// }
//
// @Test
// fun testPostApiV1Settaskparams() = testApplication {
// application {
// httpRouting()
// }
// client.post("/API/V1/setTaskParams").apply {
// TODO("Please write your test here")
// }
// }
//
// @Test
// fun testPostApiV1Start() = testApplication {
// application {
// httpRouting()
// }
// client.post("/API/V1/start").apply {
// TODO("Please write your test here")
// }
// }
//
// @Test
// fun testPostApiV1Stop() = testApplication {
// application {
// httpRouting()
// }
// client.post("/API/V1/stop").apply {
// TODO("Please write your test here")
// }
// }
//
// @Test
// fun testPostApiV1Destroy() = testApplication {
// application {
// httpRouting()
// }
// client.post("/API/V1/destroy").apply {
// TODO("Please write your test here")
// }
// }
//
// @Test
// fun testGetApiV1Listinstance() = testApplication {
// application {
// httpRouting()
// }
// client.get("/API/V1/listInstance").apply {
// TODO("Please write your test here")
// }
// }
}