sil*_*ris 4 java logging spring packages classname
我有一堆小服务,方便地称为微服务 ;-),它们都具有相同的启动行为。它们被安排在包裹中 - 每一种服务。包命名是这样的:
com.foo.bar.Application
Run Code Online (Sandbox Code Playgroud)
其中 com.foo 是域部分, bar 是实际的服务名称, Application 是我的主要实例类和 main 方法。
现在我想做的是在它们启动时打印出标准化的日志消息,显示用户可能查询的 URL 以获取有关服务的一些信息。根据定义,获取服务信息的 URL 应构造如下:
IP:PORT/bar/admin/info
Run Code Online (Sandbox Code Playgroud)
我试图用 getClass()... 等来获取这个 bar.name,但这不起作用。所以我试过这个:
LOG.info("Access URLs:\n----------------------------------------------------------\n" +
"\tLocal: \t\thttp://127.0.0.1:{}/" + getMyClass() + "/info\n" +
"\tExternal: \thttp://{}:{}/" + getMyClass() + "/info\n----------------------------------------------------------",
env.getProperty("server.port"),
InetAddress.getLocalHost().getHostAddress(),
env.getProperty("server.port")
);
/**
* Get the name of the application class as a static value, so we can show it in the log
*/
public static final Class[] getClassContext() {
return new SecurityManager() {
protected Class[] getClassContext(){return super.getClassContext();}
}.getClassContext();
};
public static final Class getMyClass() { return getClassContext()[2];}
Run Code Online (Sandbox Code Playgroud)
但是正如您可能已经猜到的那样,这打印出来的太多了:
class com.foo.bar.Application
Run Code Online (Sandbox Code Playgroud)
我想得到的地方是
bar
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点???
顺便说一句,我正在使用 Java 8 和 Spring boot - 如果有帮助的话
此致,
克里斯
您可以尝试先从类中检索包对象,然后读取其名称。以下代码将为您提供packageName变量中包含的完整包名称(例如“com.foo.bar”),以及变量中的直接父名称(例如bar)directParent:
String packageName = getMyClass().getPackage().getName();
String directParent;
if(packageName.contains(".")) {
directParent = packageName.substring(1 + packageName.lastIndexOf("."));
} else {
directParent = packageName;
}
Run Code Online (Sandbox Code Playgroud)
所以,如果你把它放在这个片段之后,你的日志语句可以只使用这些变量之一。
| 归档时间: |
|
| 查看次数: |
3038 次 |
| 最近记录: |