https://stackoverflow.com/questions/44710219/my-evaluatorfilter-doesnt-work-in-spring-boot-logback-access-xml にあるとおり、logback-access.xmlではJaninoEventEvaluator
ではなくAccessEvent
でfilterのexpressionを記述の必要がある。なので起動時にこんな感じのエラーメッセージが出る。
20:46:19,031 |-ERROR in ch.qos.logback.access.boolex.JaninoEventEvaluator@7779f32e - Could not start evaluator with expression [return formattedMessage.contains("/hoge");] org.codehaus.commons.compiler.CompileException: Line 1, Column 25: Unknown variable or type "formattedMessage"
at org.codehaus.commons.compiler.CompileException: Line 1, Column 25: Unknown variable or type "formattedMessage"
plugins {
id 'java'
id 'org.springframework.boot' version '3.0.5'
id 'io.spring.dependency-management' version '1.1.0'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.codehaus.janino:janino'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
implementation 'ch.qos.logback:logback-access'
}
tasks.named('test') {
useJUnitPlatform()
}
import org.springframework.boot.web.embedded.tomcat.ConfigurableTomcatWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import ch.qos.logback.access.tomcat.LogbackValve;
@Configuration
public class LogbackAccessConfig {
@Bean
public WebServerFactoryCustomizer<ConfigurableTomcatWebServerFactory> webServerFactoryCustomizer() {
return (factory) -> {
LogbackValve v = new LogbackValve();
// v.setFilename(new ClassPathResource("logback-access.xml").getPath());
factory.addEngineValves(v);
};
}
}
src/main/resources/conf/logback-access.xml
のサンプルは以下のとおり。URLに/hoge
を含む場合はアクセスログを出力しない。eventの出力はch.qos.logback.access.spi.AccessEvent
になる。
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.core.filter.EvaluatorFilter">
<evaluator>
<expression>
System.out.println(event);
return (event.getRequestURL().contains("/hoge"));</expression>
</evaluator>
<OnMatch>DENY</OnMatch>
</filter>
<encoder>
<Pattern>combined</Pattern>
<Pattern>[ACCESS] %h %l %u %r %t{yyyy-MM-dd HH:mm:ss.SSS} %s %b %D ms</Pattern>
</encoder>
</appender>
<appender-ref ref="STDOUT" />
</configuration>