In this post, we will look into the Logback library and how we can utilise to log messages to console and also in into a file in java projects.
You might be aware of one library log4j and used as well, now question is why logback is preferred over log4j, follow here for details.
You can use any of the java logging libraries log4j2 or logback with out changing the code. you just need to change the dependencies into pom.xml. this is possible by another intermediate library SLF4J.
both log4j2 or logback supports slf4j natively, so you need not to worry about if you use any of them.
Libraries required in pom.xml
If you want to use log4j2
<dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.14.1</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.14.1</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <version>2.14.1</version> </dependency>
If you are using logback
<!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic --> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.6</version> <scope>test</scope> </dependency>
Let’s say you are using logback library in your project –
We need a xml file with name “logback.xml”, and should be placed under
current project folder | src | main | resources folder
logback.xml content
<?xml version="1.0" encoding="UTF-8"?> <configuration scan="true"> <appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <charset>UTF-8</charset> <Pattern>%d %-4relative [%thread] %-5level %logger{45} - %msg%n</Pattern> </encoder> </appender> <root level="ALL"> <appender-ref ref="consoleAppender" /> </root> </configuration>
place this above xml to print messages to the console.
Code implementation –
Create a java file – Log.java
package baseClasses; import org.slf4j.LoggerFactory.getLogger; import org.slf4j.Logger; import static java.lang.invoke.MethodHandles.lookup; public class Log { public static void main(String args[]) { final Logger logger = getLogger(lookup().lookupClass()); logger.info("this is info message"); logger.error("this is error message"); } }
Output –
2018-12-04 13:02:28,904 223 [main] INFO logback.Logback - this is info message 2018-12-04 13:02:28,906 225 [main] ERROR logback.Logback - this is error message
Like info / error, we have few more methods or we call levels to print messages, those are debug, trace and warn [Find more details – find class Logger here]
Explanation –
The output is basically in the pattern as mentioned in the Pattern attribute of logback.xml
<Pattern>%d %-4relative [%thread] %-5level %logger{45} - %msg%n</Pattern>
thread -> main
level -> INFO or ERROR
logger -> class name from where message is sent
msg -> actual message written inside the methods like info() / error()
Till now we have seen how to print the messages to console, we will see how to print the messages into console and file as well
Print log messages to file –
Code used inside the Logback class as mentioned above will remain same, only we need to update the logback.xml
<?xml version="1.0" encoding="UTF-8"?> <configuration scan="true"> <appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <charset>UTF-8</charset> <Pattern>%d %-4relative [%thread] %-5level %logger{45} - %msg%n</Pattern> </encoder> </appender> <timestamp key="timeStamp" datePattern="dd-MM-yyy-HH-mm-ss"/> <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${user.dir}/logs/app-${timeStamp}.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> <fileNamePattern>logs/app-%i.log.gz</fileNamePattern> <minIndex>1</minIndex> <maxIndex>2</maxIndex> </rollingPolicy> <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> <maxFileSize>2MB</maxFileSize> </triggeringPolicy> <encoder> <charset>UTF-8</charset> <pattern>%d %-4relative [%thread] %-5level %logger{35} - %msg%n</pattern> </encoder> </appender> <root level="ALL"> <appender-ref ref="consoleAppender" /> <appender-ref ref="FILE"/> </root> </configuration>
If you observe the above logback.xml content, we have added another appender as name = file, and customised the file name with respect to the “timeStamp” tag and variable.
Now run the Logback.java file, observe that there is a new folder generated as logs under your current project and the message sent is printed on console and also in to the log file.
Note – If file not created, then right click on the project -> Refresh