Skip to content

Commit

Permalink
Make more friendly error track (halo-dev#1191)
Browse files Browse the repository at this point in the history
* Update gradle wrapper version to 6.6.1

* Upgrade h2 version to 1.4.197

* Make controller log more details

* Refactor FileHandler

* Fix image reader error
  • Loading branch information
JohnNiang authored Dec 12, 2020
1 parent 9951a83 commit 6fb65d0
Show file tree
Hide file tree
Showing 19 changed files with 166 additions and 164 deletions.
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ ext {
thumbnailatorVersion = "0.4.11"
image4jVersion = "0.7zensight1"
flywayVersion = "6.5.0"
h2Version = "1.4.196"
h2Version = "1.4.197"
levelDbVersion = "0.12"
annotationsVersion = "3.0.1u2"
zxingVersion = "3.4.0"
Expand Down
2 changes: 1 addition & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-6.6.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
12 changes: 4 additions & 8 deletions src/main/java/run/halo/app/controller/core/CommonController.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package run.halo.app.controller.core;

import cn.hutool.extra.servlet.ServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
Expand Down Expand Up @@ -72,12 +71,6 @@ public CommonController(ThemeService themeService,
*/
@GetMapping
public String handleError(HttpServletRequest request, HttpServletResponse response, Model model) {
log.error("Request URL: [{}], URI: [{}], Request Method: [{}], IP: [{}]",
request.getRequestURL(),
request.getRequestURI(),
request.getMethod(),
ServletUtil.getClientIP(request));

handleCustomException(request);

ErrorAttributeOptions options = getErrorAttributeOptions(request);
Expand Down Expand Up @@ -168,9 +161,12 @@ private void handleCustomException(@NonNull HttpServletRequest request) {
Throwable throwable = (Throwable) throwableObject;

if (throwable instanceof NestedServletException) {
log.error("Captured an exception", throwable);
log.error("Captured an exception: [{}]", throwable.getMessage());
Throwable rootCause = ((NestedServletException) throwable).getRootCause();
if (rootCause instanceof AbstractHaloException) {
if (!(rootCause instanceof NotFoundException)) {
log.error("Caused by", rootCause);
}
AbstractHaloException haloException = (AbstractHaloException) rootCause;
request.setAttribute("javax.servlet.error.status_code", haloException.getStatus().value());
request.setAttribute("javax.servlet.error.exception", rootCause);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,11 +140,10 @@ private <T> BaseResponse<T> handleBaseException(Throwable t) {
BaseResponse<T> baseResponse = new BaseResponse<>();
baseResponse.setMessage(t.getMessage());

log.error("Captured an exception:", t);

if (log.isDebugEnabled()) {
log.error("Captured an exception:", t);
baseResponse.setDevMessage(ExceptionUtils.getStackTrace(t));
} else {
log.error("Captured an exception: [{}]", t.getMessage());
}

return baseResponse;
Expand Down
43 changes: 32 additions & 11 deletions src/main/java/run/halo/app/core/ControllerLogAop.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,21 @@
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.StopWatch;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import run.halo.app.utils.JsonUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Objects;

/**
Expand All @@ -29,12 +32,19 @@
@Slf4j
public class ControllerLogAop {

@Pointcut("execution(* *..*.*.controller..*.*(..))")
@Pointcut("@within(org.springframework.stereotype.Controller)")
public void controller() {
}

@Around("controller()")
public Object controller(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
final Method method = signature.getMethod();
if (method == null || !log.isDebugEnabled()) {
// should never happen
return joinPoint.proceed();
}

String className = joinPoint.getTarget().getClass().getSimpleName();
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
Expand All @@ -43,14 +53,25 @@ public Object controller(ProceedingJoinPoint joinPoint) throws Throwable {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = Objects.requireNonNull(requestAttributes).getRequest();

final StopWatch watch = new StopWatch(request.getRequestURI());

watch.start("PrintRequest");
printRequestLog(request, className, methodName, args);
long start = System.currentTimeMillis();
Object returnObj = joinPoint.proceed();
printResponseLog(request, className, methodName, returnObj, System.currentTimeMillis() - start);
watch.stop();

watch.start(className + "#" + methodName);
final Object returnObj = joinPoint.proceed();
watch.stop();

watch.start("PrintResponse");
printResponseLog(request, className, methodName, returnObj);
watch.stop();
if (log.isDebugEnabled()) {
log.debug("Usage:\n{}", watch.prettyPrint());
}
return returnObj;
}


private void printRequestLog(HttpServletRequest request, String clazzName, String methodName, Object[] args) throws JsonProcessingException {
log.debug("Request URL: [{}], URI: [{}], Request Method: [{}], IP: [{}]",
request.getRequestURL(),
Expand Down Expand Up @@ -80,32 +101,32 @@ private void printRequestLog(HttpServletRequest request, String clazzName, Strin
}
}

private void printResponseLog(HttpServletRequest request, String className, String methodName, Object returnObj, long usage) throws JsonProcessingException {
private void printResponseLog(HttpServletRequest request, String className, String methodName, Object returnObj)
throws JsonProcessingException {
if (log.isDebugEnabled()) {
String returnData = "";

if (returnObj != null) {
if (returnObj instanceof ResponseEntity) {
ResponseEntity responseEntity = (ResponseEntity) returnObj;
ResponseEntity<?> responseEntity = (ResponseEntity<?>) returnObj;
if (responseEntity.getBody() instanceof Resource) {
returnData = "[ BINARY DATA ]";
} else {
} else if (responseEntity.getBody() != null) {
returnData = toString(responseEntity.getBody());
}
} else {
returnData = toString(returnObj);
}

}
log.debug("{}.{} Response: [{}], usage: [{}]ms", className, methodName, returnData, usage);
log.debug("{}.{} Response: [{}]", className, methodName, returnData);
}
}

@NonNull
private String toString(@NonNull Object obj) throws JsonProcessingException {
Assert.notNull(obj, "Return object must not be null");

String toString = "";
String toString;
if (obj.getClass().isAssignableFrom(byte[].class) && obj instanceof Resource) {
toString = "[ BINARY DATA ]";
} else {
Expand Down
20 changes: 13 additions & 7 deletions src/main/java/run/halo/app/filter/LogFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,24 +20,30 @@
*/
@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE + 9)
@Order(Ordered.HIGHEST_PRECEDENCE)
public class LogFilter extends OncePerRequestFilter {

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

String remoteAddr = ServletUtil.getClientIP(request);
final String remoteAddr = ServletUtil.getClientIP(request);

log.debug("");
log.debug("Starting url: [{}], method: [{}], ip: [{}]", request.getRequestURL(), request.getMethod(), remoteAddr);
log.debug("Starting url: [{}], method: [{}], ip: [{}]",
request.getRequestURL(),
request.getMethod(),
remoteAddr);

// Set start time
long startTime = System.currentTimeMillis();
final long startTime = System.currentTimeMillis();

// Do filter
filterChain.doFilter(request, response);

log.debug("Ending url: [{}], method: [{}], ip: [{}], status: [{}], usage: [{}] ms", request.getRequestURL(), request.getMethod(), remoteAddr, response.getStatus(), System.currentTimeMillis() - startTime);
log.debug("");
log.debug("Ending url: [{}], method: [{}], ip: [{}], status: [{}], usage: [{}] ms",
request.getRequestURL(),
request.getMethod(),
remoteAddr,
response.getStatus(),
System.currentTimeMillis() - startTime);
}
}
29 changes: 13 additions & 16 deletions src/main/java/run/halo/app/handler/file/AliOssFileHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
import run.halo.app.utils.FilenameUtils;
import run.halo.app.utils.ImageUtils;

import javax.imageio.ImageReader;
import java.util.Objects;

import static run.halo.app.model.support.HaloConst.URL_SEPARATOR;
Expand Down Expand Up @@ -72,10 +71,10 @@ public AliOssFileHandler(OptionService optionService) {
}

try {
String basename = FilenameUtils.getBasename(Objects.requireNonNull(file.getOriginalFilename()));
String extension = FilenameUtils.getExtension(file.getOriginalFilename());
String timestamp = String.valueOf(System.currentTimeMillis());
StringBuilder upFilePath = new StringBuilder();
final String basename = FilenameUtils.getBasename(Objects.requireNonNull(file.getOriginalFilename()));
final String extension = FilenameUtils.getExtension(file.getOriginalFilename());
final String timestamp = String.valueOf(System.currentTimeMillis());
final StringBuilder upFilePath = new StringBuilder();

if (StringUtils.isNotEmpty(source)) {
upFilePath.append(source)
Expand All @@ -93,32 +92,30 @@ public AliOssFileHandler(OptionService optionService) {
log.info(basePath.toString());

// Upload
PutObjectResult putObjectResult = ossClient.putObject(bucketName, upFilePath.toString(), file.getInputStream());
final PutObjectResult putObjectResult = ossClient.putObject(bucketName,
upFilePath.toString(),
file.getInputStream());

if (putObjectResult == null) {
throw new FileOperationException("上传附件 " + file.getOriginalFilename() + " 到阿里云失败 ");
}

// Response result
UploadResult uploadResult = new UploadResult();
final UploadResult uploadResult = new UploadResult();
uploadResult.setFilename(basename);
uploadResult.setFilePath(StringUtils.isBlank(styleRule) ? filePath : filePath + styleRule);
uploadResult.setKey(upFilePath.toString());
uploadResult.setMediaType(MediaType.valueOf(Objects.requireNonNull(file.getContentType())));
uploadResult.setSuffix(extension);
uploadResult.setSize(file.getSize());

// Handle thumbnail
if (FileHandler.isImageType(uploadResult.getMediaType())) {
ImageReader image = ImageUtils.getImageReaderFromFile(file.getInputStream(), extension);
assert image != null;
uploadResult.setWidth(image.getWidth(0));
uploadResult.setHeight(image.getHeight(0));
handleImageMetadata(file, uploadResult, () -> {
if (ImageUtils.EXTENSION_ICO.equals(extension)) {
uploadResult.setThumbPath(filePath);
return filePath;
} else {
uploadResult.setThumbPath(StringUtils.isBlank(thumbnailStyleRule) ? filePath : filePath + thumbnailStyleRule);
return StringUtils.isBlank(thumbnailStyleRule) ? filePath : filePath + thumbnailStyleRule;
}
}
});

log.info("Uploaded file: [{}] successfully", file.getOriginalFilename());
return uploadResult;
Expand Down
13 changes: 4 additions & 9 deletions src/main/java/run/halo/app/handler/file/BaiduBosFileHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
import run.halo.app.utils.FilenameUtils;
import run.halo.app.utils.ImageUtils;

import javax.imageio.ImageReader;
import java.util.Objects;

/**
Expand Down Expand Up @@ -86,17 +85,13 @@ public UploadResult upload(MultipartFile file) {
uploadResult.setSize(file.getSize());

// Handle thumbnail
if (FileHandler.isImageType(uploadResult.getMediaType())) {
ImageReader image = ImageUtils.getImageReaderFromFile(file.getInputStream(), extension);
assert image != null;
uploadResult.setWidth(image.getWidth(0));
uploadResult.setHeight(image.getHeight(0));
handleImageMetadata(file, uploadResult, () -> {
if (ImageUtils.EXTENSION_ICO.equals(extension)) {
uploadResult.setThumbPath(filePath);
return filePath;
} else {
uploadResult.setThumbPath(StringUtils.isBlank(thumbnailStyleRule) ? filePath : filePath + thumbnailStyleRule);
return StringUtils.isBlank(thumbnailStyleRule) ? filePath : filePath + thumbnailStyleRule;
}
}
});

return uploadResult;
} catch (Exception e) {
Expand Down
Loading

0 comments on commit 6fb65d0

Please sign in to comment.