Skip to content

Commit b59f251

Browse files
committed
perf: 优化日志内容,增加错误报告在线查看
1 parent 948b812 commit b59f251

9 files changed

Lines changed: 106 additions & 27 deletions

File tree

src/main/kotlin/com/github/fastmirrorserver/controller/ApiExceptionHandler.kt

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@
22

33
import com.github.fastmirrorserver.dto.ApiResponse
44
import com.github.fastmirrorserver.exception.ApiException
5+
import com.github.fastmirrorserver.service.ErrorReportService
56
import com.github.fastmirrorserver.util.UTC
67
import com.github.fastmirrorserver.util.uuid
78
import org.slf4j.LoggerFactory
9+
import org.springframework.beans.factory.annotation.Autowired
810
import org.springframework.web.bind.annotation.ExceptionHandler
911
import org.springframework.web.bind.annotation.RestControllerAdvice
1012
import org.springframework.web.util.NestedServletException
@@ -18,6 +20,9 @@ import javax.servlet.http.HttpServletResponse
1820
@RestControllerAdvice
1921
class ApiExceptionHandler {
2022
private val logger = LoggerFactory.getLogger(this::class.java)
23+
@Autowired
24+
private lateinit var service: ErrorReportService
25+
2126
@ExceptionHandler(ApiException::class)
2227
fun serviceExceptionHandler(e: ApiException, request: HttpServletRequest, response: HttpServletResponse): ApiResponse {
2328
response.status = e.status.value()
@@ -29,17 +34,9 @@ class ApiExceptionHandler {
2934
if(e.cause != null && e.cause is ApiException) return serviceExceptionHandler(e.cause as ApiException, request, response)
3035
logger.error("uncaught exception: ", e)
3136
response.status = 500
32-
val id = uuid().lowercase()
33-
val file = File("./error-reports/${id}")
34-
file.parentFile.mkdirs()
35-
file.createNewFile()
36-
if(file.exists()) file.bufferedWriter().use {
37-
it.write("[${LocalDateTime.now().UTC}] ${e::class.java.canonicalName}: ${e.message}")
38-
it.newLine()
39-
val writer = PrintWriter(it)
40-
e.printStackTrace(writer)
41-
writer.flush()
42-
}
37+
38+
val id = service.set(e)
39+
4340
return ApiResponse(
4441
data = mapOf<String, String>(
4542
"name" to e::class.java.name,
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.github.fastmirrorserver.controller
2+
3+
import com.github.fastmirrorserver.annotation.Authority
4+
import com.github.fastmirrorserver.service.ErrorReportService
5+
import com.github.fastmirrorserver.util.enums.Permission
6+
import org.springframework.beans.factory.annotation.Autowired
7+
import org.springframework.stereotype.Controller
8+
import org.springframework.web.bind.annotation.GetMapping
9+
import org.springframework.web.bind.annotation.PathVariable
10+
11+
@Controller
12+
class TracebackController {
13+
@Autowired
14+
private lateinit var service: ErrorReportService
15+
16+
@GetMapping("/monitor/error-report/{id}")
17+
@Authority(Permission.ROOT)
18+
fun display(@PathVariable id: String): String = service.get(id)
19+
}

src/main/kotlin/com/github/fastmirrorserver/dto/Traceback.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,5 +44,5 @@ data class Traceback(
4444
}
4545

4646
override fun toString(): String
47-
= "Session{user=$user, token=$token, remain_request=$remain_request_count, next_refresh_time=$next_refresh_time}"
47+
= "Session{user=$user, token=$token, ip=$remote_address, remain_request=$remain_request_count, next_refresh_time=$next_refresh_time}"
4848
}

src/main/kotlin/com/github/fastmirrorserver/interceptor/AuthorizationInterceptor.kt

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,11 @@ class AuthorizationInterceptor: HandlerInterceptor {
3232
val permission = authority.permission
3333

3434
val traceback = authorization.verification(request, response)
35-
36-
logger.info("request detected. session=$traceback")
37-
logger.info("method=${request.method}, path=${request.requestURI}")
35+
36+
if(!request.requestURI.startsWith("/api/v3/upload/session/file")){
37+
logger.info("request detected. session=$traceback")
38+
logger.info("method=${request.method}, path=${request.requestURI}")
39+
}
3840

3941
if(!(env == "debug" && traceback.permission == Permission.TESTER && authority.ignore_in_debug)) {
4042
if (permission == Permission.TESTER && traceback.permission != Permission.TESTER)
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package com.github.fastmirrorserver.service
2+
3+
import com.github.fastmirrorserver.util.UTC
4+
import com.github.fastmirrorserver.util.toHtml
5+
import com.github.fastmirrorserver.util.uuid
6+
import org.springframework.beans.factory.annotation.Value
7+
import org.springframework.stereotype.Service
8+
import java.io.File
9+
import java.io.PrintWriter
10+
import java.time.LocalDateTime
11+
12+
@Service
13+
class ErrorReportService {
14+
@Value("\${server.error-report.path}")
15+
private lateinit var report_root_path: String
16+
init {
17+
File(report_root_path).mkdirs()
18+
}
19+
20+
private fun File.readAsHtml(): String {
21+
val lines = readLines()
22+
return lines.drop(1).toHtml("Error Report", lines.first())
23+
}
24+
25+
fun set(err: Throwable): String {
26+
val id = uuid()
27+
val file = File("$report_root_path/$id")
28+
file.createNewFile()
29+
if(file.exists())
30+
file.bufferedWriter().use {
31+
it.write(LocalDateTime.now().UTC)
32+
it.newLine()
33+
it.write("${err::class.java.canonicalName}: ${err.message}")
34+
it.newLine()
35+
PrintWriter(it).also {writer ->
36+
err.printStackTrace(writer)
37+
}.flush()
38+
}
39+
return id
40+
}
41+
42+
fun get(id: String): String {
43+
val file = File("$report_root_path/$id")
44+
return if(file.exists())
45+
file.readAsHtml()
46+
else
47+
arrayOf("error report not found.").toHtml("Error Report", LocalDateTime.now().UTC)
48+
}
49+
}

src/main/kotlin/com/github/fastmirrorserver/service/UploadTaskService.kt

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,13 +48,13 @@ class UploadTaskService {
4848
val entity = database.all_cores
4949
.querySpecificArtifact(pojo)
5050
.firstOrNull()
51-
// 有记录 任务列表无 已启用 数据有更新
52-
if(entity == null) // 否 -- -- -- 创建任务
51+
// 有记录 任务列表无 已启用 数据有更新
52+
if(entity == null) // 否 -- -- -- 创建任务
5353
insertOrUpdate(pojo)
5454
else if(tasks.has(pojo)) // 是 否 -- -- 抛异常
5555
// throw ApiException.CONFLICT_TASK
5656
tasks.removeTask(pojo)
57-
else if(!entity.enable) // 是 是 否 -- 创建任务
57+
else if(!entity.enable) // 是 是 否 -- 创建任务
5858
insertOrUpdate(pojo)
5959
else if(isEquivalent(pojo, entity)) // 是 是 是 否 抛异常
6060
throw ApiException.UP_TO_DATE

src/main/kotlin/com/github/fastmirrorserver/util/UploadTaskContainer.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ class UploadTaskContainer {
2323
return writer.write(stream, position, length)
2424
}
2525
fun nextExpectedRange(maximum: Int = Int.MAX_VALUE) = writer.nextExpectedRange(maximum)
26-
fun release() = writer.release()
26+
fun release() { if(this::writer.isInitialized) writer.release() }
2727
fun flush() = writer.flush()
2828
}
2929
private val task_pool: TreeMap<String, Task> = TreeMap()

src/main/kotlin/com/github/fastmirrorserver/util/Utility.kt

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -27,16 +27,26 @@ fun String.template(map: Map<String, String>): String {
2727
return sb.toString()
2828
}
2929

30-
fun String.urlTemplate(manifest: Manifest)
31-
= this.template(mapOf(
32-
"name" to manifest.name,
33-
"mc_version" to manifest.mc_version,
34-
"core_version" to manifest.core_version
35-
))
36-
3730
fun String.urlTemplate(tuple: Metadata)
3831
= this.template(mapOf(
3932
"name" to tuple.name,
4033
"mc_version" to tuple.mc_version,
4134
"core_version" to tuple.core_version
42-
))
35+
))
36+
37+
private fun Iterator<String>.toHtml(title: String, subtitle: String): String {
38+
val builder = StringBuilder()
39+
builder.append("<html lang=\"en\">").append('\n')
40+
.append("<head>").append('\n')
41+
.append("<meta charset=\"UTF-8\">").append('\n')
42+
.append("<title>$title</title>").append('\n')
43+
.append("</head>").append('\n')
44+
.append("<body>").append('\n')
45+
.append("<h1>$title</h1>").append('\n')
46+
.append("<h2>$subtitle</h2>").append('\n')
47+
while(hasNext()) builder.append("<p>${next()}</p>").append('\n')
48+
builder.append("</body>").append('\n')
49+
return builder.toString()
50+
}
51+
fun Array<String>.toHtml(title: String, subtitle: String) = iterator().toHtml(title, subtitle)
52+
fun Iterable<String>.toHtml(title: String, subtitle: String) = iterator().toHtml(title, subtitle)

src/main/resources/application.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
server:
22
tomcat:
33
max-http-form-post-size: 100MB
4+
error-report:
5+
path: "./error-reports"
46
forward-headers-strategy: native
57
spring:
68
profiles:

0 commit comments

Comments
 (0)