Skip to content

feat: 支持使用注解自定义日志 logger 名字 #175

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ public class GlobalLogProperty {
*/
private boolean enable = true;

/**
* logger 名字,默认为{@link LoggingInterceptor} 的全类名
*/
private String logger = LoggingInterceptor.class.getName();

/**
* 日志打印级别,支持的日志级别参见{@link LogLevel}
* Log printing level, see {@link LogLevel} for supported log levels
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,16 @@
*/
boolean enable() default true;

/**
* 设置 logger 名字,效果相当于 {@code LoggerFactory.getLogger(logger)}。
* <p>
* 默认值为 {@link LoggingInterceptor} 的全类名。
* <p>如果为空,使用默认值。</p>
*
* @return logger 名字
*/
String logger() default "";

/**
* 日志打印级别,支持的日志级别参见{@link LogLevel}
* 如果为NULL,则取全局日志打印级别
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
package com.github.lianjiatech.retrofit.spring.boot.log;

import com.github.lianjiatech.retrofit.spring.boot.util.AnnotationExtendUtils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import retrofit2.Invocation;

import java.io.IOException;
Expand All @@ -14,7 +15,6 @@
* @author 陈添明
* @since 2022/4/30 8:21 下午
*/
@Slf4j
public class LoggingInterceptor implements Interceptor {

protected final GlobalLogProperty globalLogProperty;
Expand All @@ -33,9 +33,11 @@ public Response intercept(Chain chain) throws IOException {
if (logStrategy == LogStrategy.NONE) {
return chain.proceed(chain.request());
}

LogLevel logLevel = logging == null ? globalLogProperty.getLogLevel() : logging.logLevel();
boolean aggregate = logging == null ? globalLogProperty.isAggregate() : logging.aggregate();
HttpLoggingInterceptor.Logger matchLogger = matchLogger(logLevel);
String loggerName = logging == null || logging.logger().isEmpty() ? globalLogProperty.getLogger() : logging.logger();
HttpLoggingInterceptor.Logger matchLogger = matchLogger(loggerName, logLevel);
HttpLoggingInterceptor.Logger logger = aggregate ? new BufferingLogger(matchLogger) : matchLogger;
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(logger)
.setLevel(HttpLoggingInterceptor.Level.valueOf(logStrategy.name()));
Expand Down Expand Up @@ -66,7 +68,8 @@ protected boolean needLog(Logging logging) {
}
}

protected HttpLoggingInterceptor.Logger matchLogger(LogLevel level) {
protected HttpLoggingInterceptor.Logger matchLogger(String loggerName, LogLevel level) {
Logger log = LoggerFactory.getLogger(loggerName);
if (level == LogLevel.DEBUG) {
return log::debug;
} else if (level == LogLevel.ERROR) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
package com.github.lianjiatech.retrofit.spring.boot.test.integration.log;

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import com.github.lianjiatech.retrofit.spring.boot.log.GlobalLogProperty;
import com.github.lianjiatech.retrofit.spring.boot.log.Logging;
import com.github.lianjiatech.retrofit.spring.boot.test.integration.MockWebServerTest;
import com.github.lianjiatech.retrofit.spring.boot.test.integration.RetrofitBootApplication;
import com.github.lianjiatech.retrofit.spring.boot.test.integration.entity.User;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import static org.junit.Assert.assertEquals;

/**
* Tests for {@link Logging#logger()} based on logback
*
* @author Hason
*/
@SpringBootTest(classes = {RetrofitBootApplication.class})
@RunWith(SpringRunner.class)
public class CustomLoggerTest extends MockWebServerTest {

@Autowired
private CustomLoggerUserService service;

@Autowired
private DefaultLoggerUserService defaultLoggerUserService;

private TestAppender testAppender;

@Before
public void setup() {
testAppender = new TestAppender();
}

@Test
public void shouldEqualsDefaultLogger() {
// given
GlobalLogProperty property = new GlobalLogProperty();
Logger logger = (Logger) LoggerFactory.getLogger(property.getLogger());
logger.addAppender(testAppender);
testAppender.start();

mockServerReturnString(MIKE);

// when
defaultLoggerUserService.getName(Long100);

// then 应当使用类的logger打印日志
assertEquals(property.getLogger(), testAppender.lastEvent.getLoggerName());
}

@Test
public void shouldEqualsClassLogger() {
// given
Logger logger = (Logger) LoggerFactory.getLogger(CustomLoggerUserService.LOGGER);
logger.addAppender(testAppender);
testAppender.start();

mockServerReturnString(MIKE);

// when
service.getName(Long100);

// then 应当使用类的logger打印日志
assertEquals(CustomLoggerUserService.LOGGER, testAppender.lastEvent.getLoggerName());
}

@Test
public void shouldEqualsMethodLogger() {
// given
Logger logger = (Logger) LoggerFactory.getLogger(CustomLoggerUserService.LOGGER);
logger.addAppender(testAppender);
testAppender.start();

mockServerReturnObject(USER_MIKE);

// when
User user = service.getUser(Long100);

// then 应当使用类的logger打印日志
assertEquals(CustomLoggerUserService.LOGGER + ".getUser", testAppender.lastEvent.getLoggerName());
}

static class TestAppender extends AppenderBase<ILoggingEvent> {
private ILoggingEvent lastEvent;

@Override
protected void append(ILoggingEvent event) {
this.lastEvent = event;
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package com.github.lianjiatech.retrofit.spring.boot.test.integration.log;

import com.github.lianjiatech.retrofit.spring.boot.core.RetrofitClient;
import com.github.lianjiatech.retrofit.spring.boot.log.LogStrategy;
import com.github.lianjiatech.retrofit.spring.boot.log.Logging;
import com.github.lianjiatech.retrofit.spring.boot.test.integration.entity.User;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;

import java.util.List;

/**
* 测试自定义 logger 的客户端
*
* @author Hason
*/
@RetrofitClient(baseUrl = "${test.baseUrl}")
@Logging(logger = CustomLoggerUserService.LOGGER)
public interface CustomLoggerUserService {

String LOGGER = "CustomLoggerUserService";

/**
* 根据id查询用户姓名
*/
@POST("getName")
String getName(@Query("id") Long id);

/**
* 根据id查询用户信息
*/
@GET("getUser")
@Logging(logStrategy = LogStrategy.BODY, logger = CustomLoggerUserService.LOGGER + ".getUser")
User getUser(@Query("id") Long id);

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.github.lianjiatech.retrofit.spring.boot.test.integration.log;

import com.github.lianjiatech.retrofit.spring.boot.core.RetrofitClient;
import retrofit2.http.POST;
import retrofit2.http.Query;

/**
* 测试默认 logger 的客户端
*
* @author Hason
*/
@RetrofitClient(baseUrl = "${test.baseUrl}")
public interface DefaultLoggerUserService {

/**
* 根据id查询用户姓名
*/
@POST("getName")
String getName(@Query("id") Long id);

}