Skip to content

Instantly share code, notes, and snippets.

@irof
Last active October 24, 2022 04:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save irof/0e560541d01bb7fb905ca5fb2292276b to your computer and use it in GitHub Desktop.
Save irof/0e560541d01bb7fb905ca5fb2292276b to your computer and use it in GitHub Desktop.
ログとかの確認をするためのコントローラー実装
package customer.experience.presentation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Locale;
/**
* ログとかの確認をするためのコントローラー実装。
* プロダクションでは動かないよう、削除するか {@link org.springframework.context.annotation.Profile} などで制御すること。
*
* @see <a href="https://gist.github.com/irof/0e560541d01bb7fb905ca5fb2292276b">gist</a>
*/
@RestController
@RequestMapping("operation")
class OperationController {
private static final Logger logger = LoggerFactory.getLogger(OperationController.class);
/**
* ログの出方を確認する
* @param level ログレベル
* @param message ログメッセージ
*/
@RequestMapping("log/{level}/{message}")
void log(@PathVariable String level, @PathVariable String message) {
switch (level.toLowerCase(Locale.ROOT)) {
case "debug" -> logger.debug(message);
case "info" -> logger.info(message);
case "warn" -> logger.warn(message);
case "error" -> logger.error(message);
default -> throw new IllegalStateException("Unexpected value: " + level);
}
}
/**
* 例外ログの出方を確認する
* @param level ログレベル
* @param message ログメッセージ
* @param exception 例外型
*/
@RequestMapping("log/{level}/{message}/{exception}")
void log(@PathVariable String level, @PathVariable String message, @PathVariable String exception) {
Exception e = switch (exception.toLowerCase(Locale.ROOT)) {
case "e", "exception" -> new Exception("test");
case "r", "run", "runtime", "runtimeexception" -> new RuntimeException("test");
default -> throw new IllegalStateException("Unexpected value: " + exception);
};
switch (level.toLowerCase(Locale.ROOT)) {
case "debug" -> logger.debug(message, e);
case "info" -> logger.info(message, e);
case "warn" -> logger.warn(message, e);
case "error" -> logger.error(message, e);
default -> throw new IllegalStateException("Unexpected value: " + level);
}
}
/**
* レスポンスステータスを確認する
* @param status ステータスコード
* @return レスポンス
*/
@RequestMapping("response/{status}")
ResponseEntity<?> responseStatus(@PathVariable int status) {
logger.info("response status={}", status);
return ResponseEntity.status(status).body("response");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment