[slf4j-user] How to prefix log messages for individual Loggers?

Alexander Poulikakos alexander.poulikakos at ericsson.com
Thu May 23 23:00:05 CEST 2013


Hi slf4j users

I have a class that communicates (i.e. sending commands) with remote nodes. I can create multiple instances of this class, where each instance communicates with a specific host. I use a Logger object to log each command. My problem is that the command does not show which node it is sent to. What would be the best way to prefix the log message with an id that identifies which node is the receiver of a command? I'm trying to avoid "manually" prefixing the log message for each logger call.

The below example is a simplified version. In reality there are plenty logger calls, many different types of nodes, different types of communication. Etc.

I have tried using the MDC, but effectively, due to its static context,  I need to surround each logger call with,:
              MDC.put("id", id);
              logger.info(command);
              MDC.remove("id");
Which is not much different from prefixing each log message
              logger.info(id + ":" + command);

Any suggestions how to solve this?

Regards,
Alex

===========================================
package demo;
public class Demo {
       public static void main(String[] args) {
              Node n1 = new Node("host.com", "id1");
              n1.send("command1");

              Node n2 = new Node("anotherhost.com", "id2");
              n2.send("command2");
       }
}
===========================================

package demo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Node {
       private Logger logger = LoggerFactory.getLogger(Node.class);
       private String id;

       public Node(String host, String id) {
              this.id = id;
              // create connection to host
       }

       public void send(String command){
              logger.info(command);
              //send command to host
       }
}
===========================================


Using the following logback.xml
========================================
<configuration>
  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%d{HH:mm:ss.SSS} %X{id} %msg%n</pattern>
    </encoder>
  </appender>

  <root level="INFO">
    <appender-ref ref="STDOUT" />
  </root>
</configuration>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mailman.qos.ch/pipermail/slf4j-user/attachments/20130523/c15f1a5e/attachment.html>


More information about the slf4j-user mailing list