如何在 Spring Boot 应用程序中记录活动配置? [英] How to log the active configuration in a Spring Boot application?

查看:38
本文介绍了如何在 Spring Boot 应用程序中记录活动配置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很想为 Spring Boot 使用 YAML 配置,因为我发现让单个文件显示我的不同配置文件中哪些属性处于活动状态非常可读且有用.不幸的是,我发现在 application.yml 中设置属性可能相当脆弱.

I would really like to use YAML config for Spring Boot, as I find it quite readable and useful to have a single file showing what properties are active in my different profiles. Unfortunately, I'm finding that setting properties in application.yml can be rather fragile.

像使用制表符而不是空格这样的事情会导致属性不存在(据我所知没有警告),而且我经常发现我的活动配置文件没有被设置,因为我的一些未知问题YAML.

Things like using a tab instead of spaces will cause properties to not exist (without warnings as far as I can see), and all too often I find that my active profiles are not being set, due to some unknown issue with my YAML.

所以我想知道是否有任何钩子可以让我掌握当前活动的配置文件和属性,以便我可以记录它们.

So I was wondering whether there are any hooks that would enable me to get hold of the currently active profiles and properties, so that I could log them.

同样的,如果application.yml有错误,有没有办法导致启动失败?要么是这样,要么是我自己验证 YAML 的一种方式,这样我就可以终止启动过程.

Similarly, is there a way to cause start-up to fail if the application.yml contains errors? Either that or a means for me to validate the YAML myself, so that I could kill the start-up process.

推荐答案

我遇到了同样的问题,希望有一个调试标志,可以告诉配置文件处理系统吐出一些有用的日志记录.一种可能的方法是为您的应用程序上下文注册一个事件侦听器,并从环境中打印出配置文件.我自己没有尝试过这样做,所以你的里程可能会有所不同.我认为可能类似于此处概述的内容:

I had the same problem, and wish there was a debug flag that would tell the profile processing system to spit out some useful logging. One possible way of doing it would be to register an event listener for your application context, and print out the profiles from the environment. I haven't tried doing it this way myself, so your mileage may vary. I think maybe something like what's outlined here:

如何向应用上下文初始化事件?

然后你会在你的监听器中做这样的事情:

Then you'd do something like this in your listener:

System.out.println("Active profiles: " + Arrays.toString(ctxt.getEnvironment().getActiveProfiles()));

可能值得一试.另一种可能的方法是在需要打印配置文件的代码中声明要注入的环境.即:

Might be worth a try. Another way you could probably do it would be to declare the Environment to be injected in the code where you need to print the profiles. I.e.:

@Component
public class SomeClass {
  @Autowired
  private Environment env;
  ...
  private void dumpProfiles() {
    // Print whatever needed from env here
  }
}

这篇关于如何在 Spring Boot 应用程序中记录活动配置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆