[英]java logback custom logger name
I want to create the following logback configuration:我想创建以下 logback 配置:
<configuration>
<appender name="INCOMING_REQUESTS_LOG" class="ch.qos.logback.core.FileAppender">
<file>./logs/incoming_requests.log</file>
<append>true</append>
<!-- encoders are assigned the type
ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
<encoder>
<pattern>%date %-4relative [%thread] %-5level %logger{35} | %msg%n</pattern>
</encoder>
</appender>
<logger name="mysuperduperlogger" level="DEBUG" additivity="false">
<appender-ref ref="INCOMING_REQUESTS_LOG"/>
</logger>
</configuration>
Can I use我可以用吗
logger name="mysuperduperlogger"
as logback logger name and how to access it in my code?作为 logback 记录器名称以及如何在我的代码中访问它? In documentation I could found only loggers like "com.mypackage.myclass.aa1"
在文档中,我只能找到像“com.mypackage.myclass.aa1”这样的记录器
When you create a instance of Logger
you can do so in two ways.创建
Logger
实例时,可以通过两种方式进行。
If you use by Class like如果您按类使用
private static final Logger LOGGER = LoggerFactory.getLogger(Test.class);
and the class name including the package is org.example.Test
then to configure logs for this logger the name can be org.example.Test
并且包含包的类名是
org.example.Test
然后为此记录器配置日志名称可以是org.example.Test
If you use by String like如果您按字符串使用,例如
private static final Logger LOGGER = LoggerFactory.getLogger("TestLogger");
then to configure logs for this logger the name can be TestLogger
然后为此记录器配置日志,名称可以是
TestLogger
So if you want to use mysuperduperlogger
as logger name you have to create a Logger
instance as follows.因此,如果您想使用
mysuperduperlogger
作为记录器名称,则必须按如下方式创建一个Logger
实例。
private static final Logger LOGGER = LoggerFactory.getLogger("mysuperduperlogger");
Just to extend a bit on @karthikeyan-vaithilingam's answer and the subsequent question of @user1001, you can have a custom logger name AND the package name by simply concatenating them (though it gets into a quite lengthy construction):只是在@karthikeyan-vaithilingam 的回答和@user1001 的后续问题上稍微扩展一下,您可以通过简单地连接它们来获得自定义记录器名称和包名称(尽管它进入了一个相当冗长的结构):
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass().getPackageName() + ".mysuperduperlogger");
My recommendation: define all the logger names into a class with string constants, place it in a shared common module, and reference it from there.我的建议:将所有记录器名称定义到一个带有字符串常量的类中,将它放在一个共享的公共模块中,并从那里引用它。
Why?: The logger names are basically an API that you expose towards the admins of your application, you want to define this API carefully and make sure that any small-to-medium refactoring of the code (say, renaming a class or moving a class to a subpackage) does not break the existing logging configuration from where your app is deployed.为什么?:记录器名称基本上是您向应用程序管理员公开的 API,您希望仔细定义此 API 并确保代码的任何中小型重构(例如,重命名类或移动类到子包)不会破坏部署应用程序的现有日志记录配置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.