Issue
I am currently using a Spring Boot Application, where I am logging out every Log into the console.
But Now I wanted to log every log into a specific class file name.
Example
class A {
public void test() {
log.info("Test method");
}
}
So the log for this code will be in one of the log folder, where the file name will be A (the class Name) and log "Test method" will be inside the file A.
Solution
In java code, you do not just have the log statements but also some initializer for the log instance, like so:
class A {
private static Logger log = LogManager.getLogger(A.class);
public void test() {
log.info("blah");
}
}
class B {
private static Logger log = LogManager.getLogger(B.class);
public void test() {
log.info("blah");
}
}
class C {
private static Logger log = LogManager.getLogger(C.class);
public void test() {
log.info("blah");
}
}
Now in your logging configuration (log4j2.xml) the loggers match categories, and you can define which category goes to which appender. Finally you can setup appenders to write to file or console or other destinations, like so:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
<Appender type="File" name="File" fileName="/path/to/logfiles/AandB.log">
<Layout type="PatternLayout">
<Pattern>%d %p %C{1.} [%t] %m%n</Pattern>
</Layout>
</Appender>
</Appenders>
<Loggers>
<Logger level="info" name="A"><!-- speficially route these messages to the file appender only -->
<AppenderRef ref="File"/>
</Logger>
<Logger level="info" name="B"><!-- speficially route these messages to the file and console appenders -->
<AppenderRef ref="Console"/>
<AppenderRef ref="File"/>
</Logger>
<Root level="trace"> <!-- per default route all log statements to the console, which is where logging for C will end up -->
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
While it is possible, I do not see it very efficient to create a separate logfile (=> file appender) for each single class. But on library level this can make sense.
See details on https://logging.apache.org/log4j/2.x/manual/configuration.html
Answered By - queeg
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.