如何在Ktor中列出所有已配置路由并打印到应用日志
这个需求完全可以实现,不同技术栈有对应的原生能力或者轻量自定义方案即可达到和Spring内置路由打印一致的效果,具体实现方法如下:
1 Spring 生态实现方案
你提到的Spring Framework本身就内置了路由打印能力,无需额外引入第三方组件,根据你的应用类型做对应配置即可:
1.1 Spring MVC 单体/多模块聚合应用
直接修改配置文件调整日志级别,开启内置的路由扫描日志输出:
# application.yml 配置 logging: level: org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping: trace
应用启动时会自动打印所有通过@RequestMapping、@GetMapping、@PostMapping等注解声明的路由,包括请求方法、路径、对应处理类和方法名、路径参数规则等完整信息。
如果需要自定义打印格式(比如追加路由所属模块、API版本号),可以自定义BeanPostProcessor,在RequestMappingHandlerMapping初始化完成后遍历所有HandlerMethod,格式化后输出到日志。
1.2 Spring Cloud Gateway 网关(多模块API统一接入场景)
如果你的多模块API是通过网关统一做路由分发、版本控制,调整网关日志级别即可打印全量路由:
# application.yml 配置 logging: level: org.springframework.cloud.gateway.route.RouteDefinitionRouteLocator: info
如果需要自定义输出(比如按模块、API版本分组打印),可以监听容器启动完成事件,主动拉取所有路由定义后自定义格式输出,示例代码:
@Slf4j @Component public class CustomRoutePrinter implements ApplicationListener<ApplicationReadyEvent> { @Autowired private RouteDefinitionLocator routeDefinitionLocator; @Override public void onApplicationEvent(ApplicationReadyEvent event) { routeDefinitionLocator.getRouteDefinitions() .collectList() .subscribe(routeList -> { log.info("===== 全量配置路由列表 总数量:{} =====", routeList.size()); routeList.forEach(route -> log.info("路由ID:{},匹配规则:{},目标服务:{},版本前缀:{}", route.getId(), route.getPredicates(), route.getUri(), // 这里可以自定义提取你配置的版本号规则 route.getMetadata().getOrDefault("apiVersion", "无") )); }); } }
2 非Spring生态通用实现思路
核心逻辑和Spring的实现逻辑一致:在应用启动完成、所有路由规则加载完成后,主动获取框架的路由注册表,遍历后格式化输出即可:
- Go Gin 框架:调用
engine.Routes()获取所有注册路由,遍历打印路径、请求方法、处理函数信息 - Node.js Express 框架:遍历
app._router.stack提取路由规则,过滤掉内置中间件后输出 - 自研路由体系:在路由注册中心新增
listAllRoutes()遍历方法,在应用启动钩子中调用输出即可
内容的提问来源于stack exchange,提问作者Edgars Jasmans
相关产品推荐
相关产品推荐

