chore: ログを改善

This commit is contained in:
usbharu 2024-09-13 01:38:12 +09:00
parent 0dcd2b1b9a
commit 94365e09f2
Signed by: usbharu
GPG Key ID: 6556747BF94EEBC8
10 changed files with 94 additions and 9 deletions

View File

@ -11,9 +11,12 @@
<match hideout> <match hideout>
@type elasticsearch @type elasticsearch
host elasticsearch host elasticsearch
include_tag_key true
port 9200 port 9200
index_name logs
include_timestamp true include_timestamp true
user elastic user elastic
password Passw0rd password Passw0rd
logstash_format true
logstash_prefix hideout
flush_interval 10s
</match> </match>

View File

@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.1-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip
networkTimeout=10000 networkTimeout=10000
validateDistributionUrl=true validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME

View File

@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.1-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip
networkTimeout=10000 networkTimeout=10000
validateDistributionUrl=true validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME

View File

@ -16,8 +16,11 @@
package dev.usbharu.hideout.core.config package dev.usbharu.hideout.core.config
import ch.qos.logback.classic.helpers.MDCInsertingServletFilter
import dev.usbharu.hideout.core.infrastructure.springframework.ApplicationRequestLogInterceptor
import dev.usbharu.hideout.core.infrastructure.springframework.SPAInterceptor import dev.usbharu.hideout.core.infrastructure.springframework.SPAInterceptor
import dev.usbharu.hideout.generate.JsonOrFormModelMethodProcessor import dev.usbharu.hideout.generate.JsonOrFormModelMethodProcessor
import org.springframework.boot.web.servlet.FilterRegistrationBean
import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Configuration
import org.springframework.http.converter.HttpMessageConverter import org.springframework.http.converter.HttpMessageConverter
@ -30,7 +33,8 @@ import org.springframework.web.servlet.mvc.method.annotation.ServletModelAttribu
@Configuration @Configuration
class MvcConfigurer( class MvcConfigurer(
private val jsonOrFormModelMethodProcessor: JsonOrFormModelMethodProcessor, private val jsonOrFormModelMethodProcessor: JsonOrFormModelMethodProcessor,
private val spaInterceptor: SPAInterceptor private val spaInterceptor: SPAInterceptor,
private val applicationRequestLogInterceptor: ApplicationRequestLogInterceptor
) : WebMvcConfigurer { ) : WebMvcConfigurer {
override fun addArgumentResolvers(resolvers: MutableList<HandlerMethodArgumentResolver>) { override fun addArgumentResolvers(resolvers: MutableList<HandlerMethodArgumentResolver>) {
resolvers.add(jsonOrFormModelMethodProcessor) resolvers.add(jsonOrFormModelMethodProcessor)
@ -38,6 +42,16 @@ class MvcConfigurer(
override fun addInterceptors(registry: InterceptorRegistry) { override fun addInterceptors(registry: InterceptorRegistry) {
registry.addInterceptor(spaInterceptor) registry.addInterceptor(spaInterceptor)
registry.addInterceptor(applicationRequestLogInterceptor)
}
@Bean
fun mdcFilter(): FilterRegistrationBean<MDCInsertingServletFilter> {
val bean = FilterRegistrationBean<MDCInsertingServletFilter>()
bean.filter = MDCInsertingServletFilter()
bean.addUrlPatterns("/*");
bean.order = Int.MIN_VALUE
return bean
} }
} }

View File

@ -0,0 +1,65 @@
package dev.usbharu.hideout.core.infrastructure.springframework
import dev.usbharu.hideout.core.infrastructure.springframework.oauth2.HideoutUserDetails
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.slf4j.MDC
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.oauth2.jwt.Jwt
import org.springframework.stereotype.Component
import org.springframework.web.servlet.AsyncHandlerInterceptor
import java.util.*
@Component
class ApplicationRequestLogInterceptor : AsyncHandlerInterceptor {
override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
MDC.put(requestId, UUID.randomUUID().toString())
val userDetailId = when (val principal = SecurityContextHolder.getContext().authentication?.principal) {
is HideoutUserDetails -> {
principal.userDetailsId
}
is Jwt -> {
principal.getClaim<String>("uid")?.toLongOrNull()
}
else -> {
null
}
}
if (userDetailId != null) {
MDC.put(userId, userDetailId.toString())
}
return true
}
override fun afterCompletion(
request: HttpServletRequest,
response: HttpServletResponse,
handler: Any,
ex: Exception?
) {
removeMdc()
}
override fun afterConcurrentHandlingStarted(
request: HttpServletRequest,
response: HttpServletResponse,
handler: Any
) {
removeMdc()
}
private fun removeMdc() {
MDC.remove(requestId)
MDC.remove(userId)
}
companion object {
const val requestId: String = "requestId"
const val userId: String = "userId"
}
}

View File

@ -21,6 +21,7 @@ import dev.usbharu.hideout.core.config.ApplicationConfig
import dev.usbharu.hideout.core.domain.model.actor.ActorRepository import dev.usbharu.hideout.core.domain.model.actor.ActorRepository
import dev.usbharu.hideout.core.domain.model.userdetails.UserDetailRepository import dev.usbharu.hideout.core.domain.model.userdetails.UserDetailRepository
import kotlinx.coroutines.runBlocking import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.slf4j.MDCContext
import org.springframework.security.core.userdetails.UserDetails import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UserDetailsService import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.core.userdetails.UsernameNotFoundException import org.springframework.security.core.userdetails.UsernameNotFoundException
@ -33,7 +34,7 @@ class UserDetailsServiceImpl(
private val applicationConfig: ApplicationConfig, private val applicationConfig: ApplicationConfig,
private val transaction: Transaction, private val transaction: Transaction,
) : UserDetailsService { ) : UserDetailsService {
override fun loadUserByUsername(username: String?): UserDetails = runBlocking { override fun loadUserByUsername(username: String?): UserDetails = runBlocking(MDCContext()) {
if (username == null) { if (username == null) {
throw UsernameNotFoundException("Username not found") throw UsernameNotFoundException("Username not found")
} }

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<configuration> <configuration>
<property name="LOG_FILE" value="logs/logFile.log"/> <property name="LOG_FILE" value="logs/logFile.log"/>
<property name="CONSOLE_LOG_THRESHOLD" value="${CONSOLE_LOG_THRESHOLD:-TRACE}"/> <property name="CONSOLE_LOG_THRESHOLD" value="${CONSOLE_LOG_THRESHOLD:-INFO}"/>
<include resource="org/springframework/boot/logging/logback/defaults.xml"/> <include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<include resource="org/springframework/boot/logging/logback/console-appender.xml"/> <include resource="org/springframework/boot/logging/logback/console-appender.xml"/>
<include resource="org/springframework/boot/logging/logback/file-appender.xml"/> <include resource="org/springframework/boot/logging/logback/file-appender.xml"/>

View File

@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.1-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip
networkTimeout=10000 networkTimeout=10000
validateDistributionUrl=true validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME

View File

@ -49,6 +49,7 @@ import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.mapNotNull import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.runBlocking import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.slf4j.MDCContext
import org.springframework.http.ResponseEntity import org.springframework.http.ResponseEntity
import org.springframework.stereotype.Controller import org.springframework.stereotype.Controller
@ -164,7 +165,7 @@ class SpringAccountApi(
id: List<String>?, id: List<String>?,
withSuspended: Boolean withSuspended: Boolean
): ResponseEntity<Flow<Relationship>> { ): ResponseEntity<Flow<Relationship>> {
val principal = runBlocking { principalContextHolder.getPrincipal() } val principal = runBlocking(MDCContext()) { principalContextHolder.getPrincipal() }
return ResponseEntity.ok(id.orEmpty().asFlow().mapNotNull { fetchRelationship(it, principal).body }) return ResponseEntity.ok(id.orEmpty().asFlow().mapNotNull { fetchRelationship(it, principal).body })
} }

View File

@ -28,6 +28,7 @@ import dev.usbharu.hideout.mastodon.interfaces.api.generated.model.Status
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.runBlocking import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.slf4j.MDCContext
import org.springframework.http.ResponseEntity import org.springframework.http.ResponseEntity
import org.springframework.stereotype.Controller import org.springframework.stereotype.Controller
@ -44,7 +45,7 @@ class SpringTimelineApi(
sinceId: String?, sinceId: String?,
minId: String?, minId: String?,
limit: Int? limit: Int?
): ResponseEntity<Flow<Status>> = runBlocking { ): ResponseEntity<Flow<Status>> = runBlocking(MDCContext()) {
val principal = principalContextHolder.getPrincipal() val principal = principalContextHolder.getPrincipal()
val userDetail = transaction.transaction { val userDetail = transaction.transaction {
userDetailRepository.findByActorId(principal.actorId.id) userDetailRepository.findByActorId(principal.actorId.id)