001/** 002 * Logback: the reliable, generic, fast and flexible logging framework. 003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved. 004 * 005 * This program and the accompanying materials are dual-licensed under 006 * either the terms of the Eclipse Public License v1.0 as published by 007 * the Eclipse Foundation 008 * 009 * or (per the licensee's choosing) 010 * 011 * under the terms of the GNU Lesser General Public License version 2.1 012 * as published by the Free Software Foundation. 013 */ 014package ch.qos.logback.classic; 015 016import static org.junit.Assert.assertEquals; 017 018import org.junit.Before; 019import org.junit.Test; 020 021import ch.qos.logback.classic.spi.ILoggingEvent; 022import ch.qos.logback.core.read.ListAppender; 023 024public class LoggerMessageFormattingTest { 025 026 LoggerContext lc; 027 ListAppender<ILoggingEvent> listAppender; 028 029 @Before 030 public void setUp() { 031 lc = new LoggerContext(); 032 Logger logger = lc.getLogger(Logger.ROOT_LOGGER_NAME); 033 listAppender = new ListAppender<ILoggingEvent>(); 034 listAppender.setContext(lc); 035 listAppender.start(); 036 logger.addAppender(listAppender); 037 } 038 039 @Test 040 public void testFormattingOneArg() { 041 Logger logger = lc.getLogger(Logger.ROOT_LOGGER_NAME); 042 logger.debug("{}", Integer.valueOf(12)); 043 ILoggingEvent event = (ILoggingEvent) listAppender.list.get(0); 044 assertEquals("12", event.getFormattedMessage()); 045 } 046 047 @Test 048 public void testFormattingTwoArg() { 049 Logger logger = lc.getLogger(Logger.ROOT_LOGGER_NAME); 050 logger.debug("{}-{}", Integer.valueOf(12), Integer.valueOf(13)); 051 ILoggingEvent event = (ILoggingEvent) listAppender.list.get(0); 052 assertEquals("12-13", event.getFormattedMessage()); 053 } 054 055 @Test 056 public void testNoFormatting() { 057 Logger logger = lc.getLogger(Logger.ROOT_LOGGER_NAME); 058 logger.debug("test", Integer.valueOf(12), Integer.valueOf(13)); 059 ILoggingEvent event = (ILoggingEvent) listAppender.list.get(0); 060 assertEquals("test", event.getFormattedMessage()); 061 } 062 063 @Test 064 public void testNoFormatting2() { 065 Logger logger = lc.getLogger(Logger.ROOT_LOGGER_NAME); 066 logger.debug("test"); 067 ILoggingEvent event = (ILoggingEvent) listAppender.list.get(0); 068 assertEquals("test", event.getFormattedMessage()); 069 } 070 071 @Test 072 public void testMessageConverter() { 073 Logger logger = lc.getLogger(Logger.ROOT_LOGGER_NAME); 074 logger.debug("{}", 12); 075 ILoggingEvent event = (ILoggingEvent) listAppender.list.get(0); 076 PatternLayout layout = new PatternLayout(); 077 layout.setContext(lc); 078 layout.setPattern("%m"); 079 layout.start(); 080 String formattedMessage = layout.doLayout(event); 081 assertEquals("12", formattedMessage); 082 } 083 084}