Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java logback custom logger name

I want to create the following logback configuration:

<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? In documentation I could found only loggers like "com.mypackage.myclass.aa1"

like image 405
avalon Avatar asked Feb 27 '26 05:02

avalon


2 Answers

When you create a instance of Logger you can do so in two ways.

  1. By Class
  2. By String

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

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

So if you want to use mysuperduperlogger as logger name you have to create a Logger instance as follows.

private static final Logger LOGGER = LoggerFactory.getLogger("mysuperduperlogger");
like image 160
Karthikeyan Vaithilingam Avatar answered Feb 28 '26 17:02

Karthikeyan Vaithilingam


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):

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.

like image 25
BogdanM Avatar answered Feb 28 '26 17:02

BogdanM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!