View Javadoc
1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.classic.db;
15  
16  import static org.junit.Assert.assertEquals;
17  import static org.junit.Assert.assertTrue;
18  import static org.junit.Assert.fail;
19  
20  import java.sql.ResultSet;
21  import java.sql.SQLException;
22  import java.sql.Statement;
23  import java.util.Date;
24  import java.util.Map;
25  
26  import org.apache.log4j.MDC;
27  import org.junit.After;
28  import org.junit.Before;
29  import org.junit.Test;
30  
31  import ch.qos.logback.classic.Level;
32  import ch.qos.logback.classic.Logger;
33  import ch.qos.logback.classic.LoggerContext;
34  import ch.qos.logback.classic.spi.ILoggingEvent;
35  import ch.qos.logback.classic.spi.LoggingEvent;
36  import ch.qos.logback.core.db.DriverManagerConnectionSource;
37  import ch.qos.logback.core.testUtil.RandomUtil;
38  import ch.qos.logback.core.testUtil.StatusChecker;
39  import ch.qos.logback.core.util.StatusPrinter;
40  
41  public class DBAppenderH2Test {
42  
43      LoggerContext loggerContext = new LoggerContext();;
44      Logger logger;
45      DBAppender appender;
46      DriverManagerConnectionSource connectionSource;
47      DBAppenderH2TestFixture dbAppenderH2TestFixture;
48      int diff = RandomUtil.getPositiveInt();
49      StatusChecker checker = new StatusChecker(loggerContext);
50  
51      @Before
52      public void setUp() throws SQLException {
53          dbAppenderH2TestFixture = new DBAppenderH2TestFixture();
54          dbAppenderH2TestFixture.setUp();
55          loggerContext.setName("default");
56          logger = loggerContext.getLogger("root");
57          appender = new DBAppender();
58          appender.setName("DB");
59          appender.setContext(loggerContext);
60          connectionSource = new DriverManagerConnectionSource();
61          connectionSource.setContext(loggerContext);
62          connectionSource.setDriverClass(DBAppenderH2TestFixture.H2_DRIVER_CLASS);
63          connectionSource.setUrl(dbAppenderH2TestFixture.url);
64          System.out.println("cs.url=" + dbAppenderH2TestFixture.url);
65          connectionSource.setUser(dbAppenderH2TestFixture.user);
66          connectionSource.setPassword(dbAppenderH2TestFixture.password);
67  
68          connectionSource.start();
69          appender.setConnectionSource(connectionSource);
70          appender.start();
71      }
72  
73      @After
74      public void tearDown() throws SQLException {
75          logger = null;
76          loggerContext = null;
77          appender = null;
78          connectionSource = null;
79          dbAppenderH2TestFixture.tearDown();
80      }
81  
82      @Test
83      public void testAppendLoggingEvent() throws SQLException {
84          ILoggingEvent event = createLoggingEvent();
85  
86          appender.append(event);
87  
88          StatusPrinter.print(loggerContext);
89  
90          Statement stmt = connectionSource.getConnection().createStatement();
91          ResultSet rs = null;
92          rs = stmt.executeQuery("SELECT * FROM logging_event");
93          if (rs.next()) {
94              assertEquals(event.getTimeStamp(), rs.getLong(DBAppender.TIMESTMP_INDEX));
95              assertEquals(event.getFormattedMessage(), rs.getString(DBAppender.FORMATTED_MESSAGE_INDEX));
96              assertEquals(event.getLoggerName(), rs.getString(DBAppender.LOGGER_NAME_INDEX));
97              assertEquals(event.getLevel().toString(), rs.getString(DBAppender.LEVEL_STRING_INDEX));
98              assertEquals(event.getThreadName(), rs.getString(DBAppender.THREAD_NAME_INDEX));
99              assertEquals(DBHelper.computeReferenceMask(event), rs.getShort(DBAppender.REFERENCE_FLAG_INDEX));
100             assertEquals(String.valueOf(diff), rs.getString(DBAppender.ARG0_INDEX));
101             StackTraceElement callerData = event.getCallerData()[0];
102             assertEquals(callerData.getFileName(), rs.getString(DBAppender.CALLER_FILENAME_INDEX));
103             assertEquals(callerData.getClassName(), rs.getString(DBAppender.CALLER_CLASS_INDEX));
104             assertEquals(callerData.getMethodName(), rs.getString(DBAppender.CALLER_METHOD_INDEX));
105         } else {
106             fail("No row was inserted in the database");
107         }
108 
109         rs.close();
110         stmt.close();
111     }
112 
113     @Test
114     public void testAppendThrowable() throws SQLException {
115         ILoggingEvent event = createLoggingEvent();
116         appender.append(event);
117         Statement stmt = connectionSource.getConnection().createStatement();
118         ResultSet rs = null;
119         rs = stmt.executeQuery("SELECT * FROM LOGGING_EVENT_EXCEPTION WHERE EVENT_ID=1");
120         rs.next();
121         String expected = "java.lang.Exception: test Ex";
122         String firstLine = rs.getString(3);
123         assertTrue("[" + firstLine + "] does not match [" + expected + "]", firstLine.contains(expected));
124 
125         int i = 0;
126         while (rs.next()) {
127             expected = event.getThrowableProxy().getStackTraceElementProxyArray()[i].toString();
128             String st = rs.getString(3);
129             assertTrue("[" + st + "] does not match [" + expected + "]", st.contains(expected));
130             i++;
131         }
132         assertTrue(i != 0);
133 
134         rs.close();
135         stmt.close();
136     }
137 
138     @Test
139     public void withNullArgument() throws SQLException {
140         ILoggingEvent event = createLoggingEvent("Processing code {}; code type is {}; request date {}; record from date {}", new Object[] { 1, 2, new Date(),
141                 null });
142         appender.append(event);
143 
144         Statement stmt = connectionSource.getConnection().createStatement();
145         ResultSet rs = null;
146         rs = stmt.executeQuery("SELECT * FROM logging_event");
147         if (rs.next()) {
148             assertEquals(event.getTimeStamp(), rs.getLong(DBAppender.TIMESTMP_INDEX));
149             assertEquals(event.getFormattedMessage(), rs.getString(DBAppender.FORMATTED_MESSAGE_INDEX));
150         }
151     }
152 
153     @Test
154     public void testContextInfo() throws SQLException {
155         loggerContext.putProperty("testKey1", "testValue1");
156         MDC.put("k" + diff, "v" + diff);
157         ILoggingEvent event = createLoggingEvent();
158 
159         appender.append(event);
160 
161         Statement stmt = connectionSource.getConnection().createStatement();
162         ResultSet rs = null;
163         rs = stmt.executeQuery("SELECT * FROM LOGGING_EVENT_PROPERTY WHERE EVENT_ID=1");
164         Map<String, String> map = appender.mergePropertyMaps(event);
165         int i = 0;
166         while (rs.next()) {
167             String key = rs.getString(2);
168             assertEquals(map.get(key), rs.getString(3));
169             i++;
170         }
171         assertTrue(map.size() != 0);
172         assertEquals(map.size(), i);
173         rs.close();
174         stmt.close();
175     }
176 
177     @Test
178     public void testAppendMultipleEvents() throws SQLException {
179         for (int i = 0; i < 10; i++) {
180             ILoggingEvent event = createLoggingEvent();
181             appender.append(event);
182         }
183 
184         Statement stmt = connectionSource.getConnection().createStatement();
185         ResultSet rs = null;
186         rs = stmt.executeQuery("SELECT * FROM logging_event");
187         int count = 0;
188         while (rs.next()) {
189             count++;
190         }
191         assertEquals(10, count);
192 
193         rs.close();
194         stmt.close();
195     }
196 
197     // http://jira.qos.ch/browse/LOGBACK-805
198     @Test
199     public void emptyCallerDataShouldBeHandledGracefully() {
200         LoggingEvent event = createLoggingEvent();
201         event.setCallerData(new StackTraceElement[0]);
202         appender.append(event);
203 
204         event.setCallerData(new StackTraceElement[] { null });
205         appender.append(event);
206 
207         checker.assertIsErrorFree();
208     }
209 
210     private LoggingEvent createLoggingEvent(String msg, Object[] args) {
211         return new LoggingEvent(this.getClass().getName(), logger, Level.DEBUG, msg, new Exception("test Ex"), args);
212     }
213 
214     private LoggingEvent createLoggingEvent() {
215         return createLoggingEvent("test message", new Integer[] { diff });
216     }
217 
218 }