Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get slf4j/logback to print on the console?

I'm new to slf4j/logback, so I have a few questions. The main one is, can I get it to print to the console and a log file simultaneously?

Currently, I can get it to print to a log file. Here's the logback.xml:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="fileAppender" class="ch.qos.logback.core.FileAppender">
        <file>/Users/admin/testlogs/myLogFile.log</file>
        <append>true</append>
        <encoder>
            <pattern>%d [%thread] %-5level  %logger{35} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="TRACE">
        <appender-ref ref="fileAppender" />
    </root>
</configuration>

In the program, if I have this command:

slf4jLogger2.warn("test");

It puts this output into the logfile:

2018-02-03 21:21:10,145 [Thread name] WARN  c.s.a.t.s.MyProgram - test

My main question is, how do I get this to the console as well?

Also, is it possible to put formatted data into the message, as in a printf statement?

For example,

out.printf("Sent: (%.2f/sec for %.1f |seconds)%n", floatPerSec, elTime);
like image 707
Jack BeNimble Avatar asked Feb 04 '18 04:02

Jack BeNimble


1 Answers

By adding ConsoleAppender to your configuration file which becomes.

<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
       <encoder>
          <pattern>%d [%thread] %-5level  %logger{35} - %msg%n</pattern>
       </encoder>
    </appender>


    <appender name="fileAppender" class="ch.qos.logback.core.FileAppender">
        <file>/Users/admin/testlogs/myLogFile.log</file>
        <append>true</append>
        <encoder>
            <pattern>%d [%thread] %-5level  %logger{35} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="TRACE">
        <appender-ref ref="fileAppender" />
        <appender-ref ref="STDOUT" />
    </root>
</configuration>

Do not forget to reference the new appender named STDOUT within the <root> logger.

like image 145
Ceki Avatar answered Oct 22 '22 05:10

Ceki