Exemple #1
0
  public static void main(String[] args) {
    LoggerContext loggerContext = new LoggerContext();
    Display display = new Display();
    ResourceUtil.init(display);
    Shell shell = new Shell(display);
    final Tree tree = new Tree(shell, SWT.BORDER);
    Rectangle clientArea = shell.getClientArea();
    tree.setBounds(clientArea.x, clientArea.y, 200, 200);

    LoggerTree loggerTree = new LoggerTree(loggerContext, tree);
    tree.setMenu(TreeMenuBuilder.buildTreeMenu(loggerTree, null));
    loggerTree.update("com.foo.Bar");
    loggerTree.update("com.foo.Bar");

    loggerContext.getLogger("org.apache.struts").setLevel(Level.ERROR);

    loggerTree.update("org.apache.struts.BlahAction");

    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch()) display.sleep();
    }
    display.dispose();
  }
 @Before
 public void setUp() throws Exception {
   context = new LoggerContext();
   context.setName("test");
   context.start();
   logger = context.getLogger(TurboFilteringInLoggerTest.class);
 }
  public void addLogstashAppender(LoggerContext context) {
    log.info("Initializing Logstash logging");

    LogstashSocketAppender logstashAppender = new LogstashSocketAppender();
    logstashAppender.setName("LOGSTASH");
    logstashAppender.setContext(context);
    String customFields = "{\"app_name\":\"" + appName + "\",\"app_port\":\"" + serverPort + "\"}";

    // Set the Logstash appender config from JHipster properties
    logstashAppender.setSyslogHost(jHipsterProperties.getLogging().getLogstash().getHost());
    logstashAppender.setPort(jHipsterProperties.getLogging().getLogstash().getPort());
    logstashAppender.setCustomFields(customFields);

    // Limit the maximum length of the forwarded stacktrace so that it won't exceed the 8KB UDP
    // limit of logstash
    ShortenedThrowableConverter throwableConverter = new ShortenedThrowableConverter();
    throwableConverter.setMaxLength(7500);
    throwableConverter.setRootCauseFirst(true);
    logstashAppender.setThrowableConverter(throwableConverter);

    logstashAppender.start();

    // Wrap the appender in an Async appender for performance
    AsyncAppender asyncLogstashAppender = new AsyncAppender();
    asyncLogstashAppender.setContext(context);
    asyncLogstashAppender.setName("ASYNC_LOGSTASH");
    asyncLogstashAppender.setQueueSize(
        jHipsterProperties.getLogging().getLogstash().getQueueSize());
    asyncLogstashAppender.addAppender(logstashAppender);
    asyncLogstashAppender.start();

    context.getLogger("ROOT").addAppender(asyncLogstashAppender);
  }
Exemple #4
0
 private void dispatchEvents(LoggerContext lc) {
   try {
     socket.setSoTimeout(acceptConnectionTimeout);
     ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
     socket.setSoTimeout(0);
     addInfo(receiverId + "connection established");
     while (true) {
       ILoggingEvent event = (ILoggingEvent) ois.readObject();
       Logger remoteLogger = lc.getLogger(event.getLoggerName());
       if (remoteLogger.isEnabledFor(event.getLevel())) {
         remoteLogger.callAppenders(event);
       }
     }
   } catch (EOFException ex) {
     addInfo(receiverId + "end-of-stream detected");
   } catch (IOException ex) {
     addInfo(receiverId + "connection failed: " + ex);
   } catch (ClassNotFoundException ex) {
     addInfo(receiverId + "unknown event class: " + ex);
   } finally {
     CloseUtil.closeQuietly(socket);
     socket = null;
     addInfo(receiverId + "connection closed");
   }
 }
 /**
  * Fixes the Chameleon logging configuration to write the logs in the logs/wisdom.log file instead
  * of chameleon.log file.
  *
  * @param basedir the base directory of the chameleon
  */
 private static void fixLoggingSystem(File basedir) {
   ILoggerFactory factory = LoggerFactory.getILoggerFactory();
   if (factory instanceof LoggerContext) {
     // We know that we are using logback from here.
     LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
     ch.qos.logback.classic.Logger logbackLogger = lc.getLogger(Logger.ROOT_LOGGER_NAME);
     if (logbackLogger == null) {
       return;
     }
     Appender<ILoggingEvent> appender = logbackLogger.getAppender("FILE");
     if (appender instanceof RollingFileAppender) {
       RollingFileAppender<ILoggingEvent> fileAppender =
           (RollingFileAppender<ILoggingEvent>) appender;
       String file = new File(basedir, "logs/wisdom.log").getAbsolutePath();
       fileAppender.stop();
       // Remove the created log directory.
       // We do that afterwards because on Windows the file cannot be deleted while we still have a
       // logger
       // using it.
       FileUtils.deleteQuietly(new File("logs"));
       fileAppender.setFile(file);
       fileAppender.setContext(lc);
       fileAppender.start();
     }
   }
 }
Exemple #6
0
  public void testAspects() throws Exception {

    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    JoranConfigurator configurator = new JoranConfigurator();
    configurator.setContext(lc);

    // the context was probably already configured by default configuration
    // rules
    lc.reset();

    configurator.doConfigure(getClass().getResource("logback.xml"));

    ListAppender<LoggingEvent> listAppender =
        (ListAppender<LoggingEvent>)
            lc.getLogger(StopWatch.DEFAULT_LOGGER_NAME).getAppender("listAppender");

    ProfiledObject.simpleTestDefaultTagStatic(10);
    assertTrue(
        "Expected tag not found in " + listAppender.list.get(0).getMessage(),
        listAppender.list.get(0).getMessage().indexOf("tag[simpleTestDefaultTagStatic]") >= 0);

    new ProfiledObject().simpleTestUnprofiled(10);
    assertTrue(
        "Expected tag not found in " + listAppender.list.get(1).getMessage(),
        listAppender.list.get(1).getMessage().indexOf("tag[simpleTestUnprofiled]") >= 0);

    assertEquals("Expected two logging events", 2, listAppender.list.size());
  }
 @RequestMapping(value = "/logs", method = RequestMethod.PUT)
 @ResponseStatus(HttpStatus.NO_CONTENT)
 @Timed
 public void changeLevel(@RequestBody LoggerDTO jsonLogger) {
   LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
   context.getLogger(jsonLogger.getName()).setLevel(Level.valueOf(jsonLogger.getLevel()));
 }
  void checkLevelChange(String loggerName, Level level) {
    Logger logger = context.getLogger(loggerName);
    logger.setLevel(level);

    assertEquals(UpdateType.LEVEL_CHANGE, listener.updateType);
    assertEquals(listener.logger, logger);
    assertEquals(listener.level, level);
  }
  void checkLevelChange(String loggerName, Level level) {
    Logger logger = loggerContext.getLogger(loggerName);
    logger.setLevel(level);
    java.util.logging.Logger julLogger = JULHelper.asJULLogger(logger);
    java.util.logging.Level julLevel = JULHelper.asJULLevel(level);

    assertEquals(julLevel, julLogger.getLevel());
  }
 private ILoggingEvent createLoggingEvent() {
   return new LoggingEvent(
       this.getClass().getName(),
       lc.getLogger(Logger.ROOT_LOGGER_NAME),
       Level.DEBUG,
       "test message",
       null,
       null);
 }
  /**
   * Add an appender to Logback logging framework that will track the types of log messages made.
   */
  @PostConstruct
  public final void addMetricsAppenderToLogback() {
    final LoggerContext factory = (LoggerContext) LoggerFactory.getILoggerFactory();
    final Logger root = factory.getLogger(Logger.ROOT_LOGGER_NAME);

    final InstrumentedAppender metrics = new InstrumentedAppender(this.metricRegistry);
    metrics.setContext(root.getLoggerContext());
    metrics.start();
    root.addAppender(metrics);
  }
Exemple #12
0
  private static void initLogging() {
    final File logDir =
        new File(
            System.getProperty(
                "user.home")); // new File("."); //getDir("log", Constants.TEST ?
                               // Context.MODE_WORLD_READABLE : MODE_PRIVATE);
    final File logFile = new File(logDir, "wowdoge.log");

    final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();

    final PatternLayoutEncoder filePattern = new PatternLayoutEncoder();
    filePattern.setContext(context);
    filePattern.setPattern("%d{HH:mm:ss.SSS} [%thread] %logger{0} - %msg%n");
    filePattern.start();

    final RollingFileAppender<ILoggingEvent> fileAppender =
        new RollingFileAppender<ILoggingEvent>();
    fileAppender.setContext(context);
    fileAppender.setFile(logFile.getAbsolutePath());

    final TimeBasedRollingPolicy<ILoggingEvent> rollingPolicy =
        new TimeBasedRollingPolicy<ILoggingEvent>();
    rollingPolicy.setContext(context);
    rollingPolicy.setParent(fileAppender);
    rollingPolicy.setFileNamePattern(logDir.getAbsolutePath() + "/wallet.%d.log.gz");
    rollingPolicy.setMaxHistory(7);
    rollingPolicy.start();

    fileAppender.setEncoder(filePattern);
    fileAppender.setRollingPolicy(rollingPolicy);
    fileAppender.start();

    final PatternLayoutEncoder logcatTagPattern = new PatternLayoutEncoder();
    logcatTagPattern.setContext(context);
    logcatTagPattern.setPattern("%logger{0}");
    logcatTagPattern.start();

    final PatternLayoutEncoder logcatPattern = new PatternLayoutEncoder();
    logcatPattern.setContext(context);
    logcatPattern.setPattern("[%thread] %msg%n");
    logcatPattern.start();

    // final LogcatAppender logcatAppender = new LogcatAppender();
    // logcatAppender.setContext(context);
    // logcatAppender.setTagEncoder(logcatTagPattern);
    // logcatAppender.setEncoder(logcatPattern);
    // logcatAppender.start();

    final ch.qos.logback.classic.Logger log = context.getLogger(Logger.ROOT_LOGGER_NAME);
    log.addAppender(fileAppender);
    // log.addAppender(logcatAppender);
    log.setLevel(Level.INFO); // Level.INFO);

    SysOutOverSLF4J.sendSystemOutAndErrToSLF4J();
  }
  @Before
  public void fixture() {
    lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    lc.reset();

    listAppender = new DummyLBAppender();
    listAppender.setContext(lc);
    listAppender.start();
    rootLogger = lc.getLogger("root");
    rootLogger.addAppender(listAppender);
  }
  // see http://jira.qos.ch/browse/LBCLASSIC-256
  @Test
  public void gc() {
    Logger logger = loggerContext.getLogger("gc" + rand);
    logger.setLevel(Level.INFO);
    // invoke GC so that the relevant julLogger can be garbage collected.
    System.gc();
    java.util.logging.Logger julLogger = JULHelper.asJULLogger(logger);
    java.util.logging.Level julLevel = JULHelper.asJULLevel(Level.INFO);

    assertEquals(julLevel, julLogger.getLevel());
  }
 @Test
 public void consolePatternCanBeOverridden() throws JoranException {
   JoranConfigurator configurator = new JoranConfigurator();
   LoggerContext context = new LoggerContext();
   configurator.setContext(context);
   configurator.doConfigure(new File("src/test/resources/custom-console-log-pattern.xml"));
   Appender<ILoggingEvent> appender = context.getLogger("ROOT").getAppender("CONSOLE");
   assertThat(appender).isInstanceOf(ConsoleAppender.class);
   Encoder<?> encoder = ((ConsoleAppender<?>) appender).getEncoder();
   assertThat(encoder).isInstanceOf(PatternLayoutEncoder.class);
   assertThat(((PatternLayoutEncoder) encoder).getPattern()).isEqualTo("foo");
 }
  private void initLogging() {
    // We can't log into the wallet specific directories because
    // logging is initialized well before we've selected one.

    final File logDir = getDir("log", MODE_PRIVATE); // Context.MODE_WORLD_READABLE
    final File logFile = new File(logDir, "wallet32.log");

    final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();

    final PatternLayoutEncoder filePattern = new PatternLayoutEncoder();
    filePattern.setContext(context);
    filePattern.setPattern("%d{HH:mm:ss.SSS} [%thread] %logger{0} - %msg%n");
    filePattern.start();

    final RollingFileAppender<ILoggingEvent> fileAppender =
        new RollingFileAppender<ILoggingEvent>();
    fileAppender.setContext(context);
    fileAppender.setFile(logFile.getAbsolutePath());

    final TimeBasedRollingPolicy<ILoggingEvent> rollingPolicy =
        new TimeBasedRollingPolicy<ILoggingEvent>();
    rollingPolicy.setContext(context);
    rollingPolicy.setParent(fileAppender);
    rollingPolicy.setFileNamePattern(logDir.getAbsolutePath() + "/wallet32.%d.log.gz");
    rollingPolicy.setMaxHistory(7);
    rollingPolicy.start();

    fileAppender.setEncoder(filePattern);
    fileAppender.setRollingPolicy(rollingPolicy);
    fileAppender.start();

    final PatternLayoutEncoder logcatTagPattern = new PatternLayoutEncoder();
    logcatTagPattern.setContext(context);
    logcatTagPattern.setPattern("%logger{0}");
    logcatTagPattern.start();

    final PatternLayoutEncoder logcatPattern = new PatternLayoutEncoder();
    logcatPattern.setContext(context);
    logcatPattern.setPattern("[%thread] %msg%n");
    logcatPattern.start();

    final LogcatAppender logcatAppender = new LogcatAppender();
    logcatAppender.setContext(context);
    logcatAppender.setTagEncoder(logcatTagPattern);
    logcatAppender.setEncoder(logcatPattern);
    logcatAppender.start();

    final ch.qos.logback.classic.Logger log = context.getLogger(Logger.ROOT_LOGGER_NAME);
    log.addAppender(fileAppender);
    log.addAppender(logcatAppender);
    log.setLevel(Level.INFO);
  }
  public void configure() throws InterruptedException {

    sa.setSyslogHost("localhost");
    sa.setFacility("AUTH");
    sa.setPort(10514);
    sa.setSuffixPattern("%-5level [%logger:%line] [%thread] %msg %ex{short}%n");
    sa.start();
    assertTrue(sa.isStarted());

    String loggerName = this.getClass().getName();
    Logger logger = lc.getLogger(loggerName);
    logger.addAppender(sa);
  }
  private void doScenarioedTest(int len) {
    LoggerContext lc = new LoggerContext();
    ControlLoggerContext controlContext = new ControlLoggerContext();
    Scenario s = ScenarioMaker.makeRealisticCreationScenario(len);
    List actionList = s.getActionList();
    int size = actionList.size();
    for (int i = 0; i < size; i++) {
      ScenarioAction action = (ScenarioAction) actionList.get(i);
      if (action instanceof CreateLogger) {
        CreateLogger cl = (CreateLogger) action;
        lc.getLogger(cl.getLoggerName());
        controlContext.getLogger(cl.getLoggerName());
      } else if (action instanceof SetLevel) {
        SetLevel sl = (SetLevel) action;
        Logger l = lc.getLogger(sl.getLoggerName());
        ControlLogger controlLogger = controlContext.getLogger(sl.getLoggerName());
        l.setLevel(sl.getLevel());
        controlLogger.setLevel(sl.getLevel());
      }
    }

    compareLoggerContexts(controlContext, lc);
  }
  @Test
  public void tException() throws InterruptedException {
    int port = RandomUtil.getRandomServerPort();

    MockSyslogServer mockServer = new MockSyslogServer(21, port);
    mockServer.start();
    // give MockSyslogServer head start
    Thread.sleep(100);

    LoggerContext lc = new LoggerContext();
    lc.setName("test");
    SyslogAppender sa = new SyslogAppender();
    sa.setContext(lc);
    sa.setSyslogHost("localhost");
    sa.setFacility("MAIL");
    sa.setPort(port);
    sa.setSuffixPattern("[%thread] %logger %msg");
    sa.start();
    assertTrue(sa.isStarted());

    String loggerName = this.getClass().getName();
    Logger logger = lc.getLogger(loggerName);
    logger.addAppender(sa);
    String logMsg = "hello";
    String exMsg = "just testing";
    Exception ex = new Exception(exMsg);
    logger.debug(logMsg, ex);
    // StatusPrinter.print(lc.getStatusManager());

    // wait max 2 seconds for mock server to finish. However, it should
    // much sooner than that.
    mockServer.join(8000);
    assertTrue(mockServer.isFinished());

    // message + 20 lines of stacktrace
    assertEquals(21, mockServer.getMessageList().size());
    // int i = 0;
    // for (String line: mockServer.msgList) {
    // System.out.println(i++ + ": " + line);
    // }

    String msg = mockServer.getMessageList().get(0);
    String expected = "<" + (SyslogConstants.LOG_MAIL + SyslogConstants.DEBUG_SEVERITY) + ">";
    assertTrue(msg.startsWith(expected));

    String expectedPrefix = "<\\d{2}>\\w{3} \\d{2} \\d{2}(:\\d{2}){2} [\\w.-]* ";
    String threadName = Thread.currentThread().getName();
    String regex = expectedPrefix + "\\[" + threadName + "\\] " + loggerName + " " + logMsg;
    checkRegexMatch(msg, regex);
  }
  @Test
  public void testOriginHost() throws Exception {

    Logger logger = lc.getLogger(getClass());

    logger.info("Blubb Test");
    assertEquals(1, GelfTestSender.getMessages().size());

    GelfMessage gelfMessage = GelfTestSender.getMessages().get(0);

    String crossCheckHostName = gelfMessage.getAdditonalFields().get("crossCheckHostName");

    String json = gelfMessage.toJson();
    assertThat(
        json,
        StringContains.containsString("\"_crossCheckHostName\":\"" + crossCheckHostName + "\""));
    assertThat(json, StringContains.containsString("\"host\":\"" + crossCheckHostName + "\""));
  }
  static void perfCase(boolean safetyMode) throws Exception {
    LoggerContext lc = buildLoggerContext(FILENAME + "-" + safetyMode + ".log", safetyMode);
    Logger logger = lc.getLogger(FileAppenderPerf.class);

    long start = System.nanoTime();
    for (int i = 0; i < LEN; i++) {
      logger.debug(msgLong + " " + i);
    }
    // in microseconds
    double durationPerLog = (System.nanoTime() - start) / (LEN * 1000.0);

    lc.stop();

    System.out.println(
        "Average duration of "
            + (durationPerLog)
            + " microseconds per log. Prudent mode="
            + safetyMode);
    System.out.println("------------------------------------------------");
  }
  @Test
  public void basic() throws InterruptedException {
    int port = RandomUtil.getRandomServerPort();

    MockSyslogServer mockServer = new MockSyslogServer(1, port);
    mockServer.start();
    // give MockSyslogServer head start
    Thread.sleep(100);

    LoggerContext lc = new LoggerContext();
    lc.setName("test");
    SyslogAppender sa = new SyslogAppender();
    sa.setContext(lc);
    sa.setSyslogHost("localhost");
    sa.setFacility("MAIL");
    sa.setPort(port);
    sa.setSuffixPattern("[%thread] %logger %msg");
    sa.start();
    assertTrue(sa.isStarted());

    String loggerName = this.getClass().getName();
    Logger logger = lc.getLogger(loggerName);
    logger.addAppender(sa);
    String logMsg = "hello";
    logger.debug(logMsg);

    // wait max 2 seconds for mock server to finish. However, it should
    // much sooner than that.
    mockServer.join(8000);
    assertTrue(mockServer.isFinished());
    assertEquals(1, mockServer.getMessageList().size());
    String msg = mockServer.getMessageList().get(0);

    String threadName = Thread.currentThread().getName();

    String expected = "<" + (SyslogConstants.LOG_MAIL + SyslogConstants.DEBUG_SEVERITY) + ">";
    assertTrue(msg.startsWith(expected));

    String first = "<\\d{2}>\\w{3} \\d{2} \\d{2}(:\\d{2}){2} [\\w.-]* ";
    checkRegexMatch(msg, first + "\\[" + threadName + "\\] " + loggerName + " " + logMsg);
  }
  @Before
  public void setUp() throws SQLException {
    dbAppenderHSQLTestFixture = new DBAppenderHSQLTestFixture();
    dbAppenderHSQLTestFixture.setUp();

    lc = new LoggerContext();
    lc.setName("default");
    logger = lc.getLogger("root");
    appender = new DBAppender();
    appender.setName("DB");
    appender.setContext(lc);
    connectionSource = new DriverManagerConnectionSource();
    connectionSource.setContext(lc);
    connectionSource.setDriverClass(DBAppenderHSQLTestFixture.HSQLDB_DRIVER_CLASS);
    connectionSource.setUrl(dbAppenderHSQLTestFixture.url);
    connectionSource.setUser(dbAppenderHSQLTestFixture.user);
    connectionSource.setPassword(dbAppenderHSQLTestFixture.password);
    connectionSource.start();
    appender.setConnectionSource(connectionSource);
    appender.start();
  }
  static LoggerContext buildLoggerContext(String filename, boolean safetyMode) {
    LoggerContext loggerContext = new LoggerContext();

    FileAppender<ILoggingEvent> fa = new FileAppender<ILoggingEvent>();

    PatternLayoutEncoder patternLayout = new PatternLayoutEncoder();
    patternLayout.setPattern("%5p %c - %m%n");
    patternLayout.setContext(loggerContext);
    patternLayout.start();

    fa.setEncoder(patternLayout);
    fa.setFile(filename);
    fa.setAppend(false);
    fa.setPrudent(safetyMode);
    fa.setContext(loggerContext);
    fa.start();

    ch.qos.logback.classic.Logger root = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME);
    root.addAppender(fa);

    return loggerContext;
  }
  @SuppressWarnings("unchecked")
  private static LoggingEvent readLoggingEvent(ExcerptTailer ex, LoggerContext ctx) {
    LoggingEventRecord rec = LoggingEventRecord.read(ex);

    Logger logger = ctx.getLogger(rec.getLoggerName());
    LoggingEvent evt =
        new LoggingEvent(
            logger.getClass().getName(),
            logger,
            Level.toLevel(rec.getLevel()),
            rec.getMessage(),
            rec.getCause(),
            rec.getArgs());
    evt.setTimeStamp(rec.getTimestamp());
    evt.setThreadName(rec.getThreadName());
    evt.setMDCPropertyMap(rec.getMdcProps());
    if (null != rec.getCause()) {
      evt.setThrowableProxy(new ThrowableProxy(rec.getCause()));
    }
    evt.setCallerData(rec.getCallerData());

    return evt;
  }
  void setLogLevelOverride(final String loggerName, final String level) throws Exception {
    // get logger
    final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    final StatusManager sm = lc.getStatusManager();
    final Logger logger = lc.getLogger(loggerName);

    // get levels
    final Level currentLevel = logger.getLevel();
    final Level newLevel = Level.toLevel(level, null);

    if (newLevel == null) {
      // reset any current override
      final String[] removed = overriddenLogLevels.remove(loggerName);
      if (removed != null) {
        final Level toRestore = Level.toLevel(removed[1], null);
        if (sm != null) {
          sm.add(
              new InfoStatus(
                  String.format(
                      "Resetting level for logger '%s'.", loggerName, logger.getEffectiveLevel()),
                  this));
        }
        logger.setLevel(toRestore);
      }
    } else if (newLevel != currentLevel) {
      // apply new override
      overriddenLogLevels.put(
          loggerName, new String[] {level, null != currentLevel ? currentLevel.levelStr : null});
      if (sm != null) {
        sm.add(
            new InfoStatus(
                String.format("Overriding level for logger '%s' to '%s'.", loggerName, newLevel),
                this));
      }
      logger.setLevel(newLevel);
    }
  }
public class SMTPAppender_GreenTest {

  static final String HEADER = "HEADER\n";
  static final String FOOTER = "FOOTER\n";
  static final String DEFAULT_PATTERN = "%-4relative %mdc [%thread] %-5level %class - %msg%n";

  static final boolean SYNCHRONOUS = false;
  static final boolean ASYNCHRONOUS = true;

  int port = RandomUtil.getRandomServerPort();
  // GreenMail cannot be static. As a shared server induces race conditions
  GreenMail greenMailServer;

  SMTPAppender smtpAppender;
  LoggerContext loggerContext = new LoggerContext();
  Logger logger = loggerContext.getLogger(this.getClass());

  @Before
  public void setUp() throws Exception {

    OnConsoleStatusListener.addNewInstanceToContext(loggerContext);
    MDC.clear();
    ServerSetup serverSetup = new ServerSetup(port, "localhost", ServerSetup.PROTOCOL_SMTP);
    greenMailServer = new GreenMail(serverSetup);
    greenMailServer.start();
    // give the server a head start
    if (EnvUtilForTests.isRunningOnSlowJenkins()) {
      Thread.sleep(2000);
    } else {
      Thread.sleep(50);
    }
  }

  @After
  public void tearDown() throws Exception {
    greenMailServer.stop();
  }

  void buildSMTPAppender(String subject, boolean synchronicity) throws Exception {
    smtpAppender = new SMTPAppender();
    smtpAppender.setContext(loggerContext);
    smtpAppender.setName("smtp");
    smtpAppender.setFrom("*****@*****.**");
    smtpAppender.setSMTPHost("localhost");
    smtpAppender.setSMTPPort(port);
    smtpAppender.setSubject(subject);
    smtpAppender.addTo("*****@*****.**");
    smtpAppender.setAsynchronousSending(synchronicity);
  }

  private Layout<ILoggingEvent> buildPatternLayout(String pattern) {
    PatternLayout layout = new PatternLayout();
    layout.setContext(loggerContext);
    layout.setFileHeader(HEADER);
    layout.setOutputPatternAsHeader(false);
    layout.setPattern(pattern);
    layout.setFileFooter(FOOTER);
    layout.start();
    return layout;
  }

  private Layout<ILoggingEvent> buildHTMLLayout() {
    HTMLLayout layout = new HTMLLayout();
    layout.setContext(loggerContext);
    layout.setPattern("%level%class%msg");
    layout.start();
    return layout;
  }

  private void waitForServerToReceiveEmails(int emailCount) throws InterruptedException {
    greenMailServer.waitForIncomingEmail(5000, emailCount);
  }

  private MimeMultipart verifyAndExtractMimeMultipart(String subject)
      throws MessagingException, IOException, InterruptedException {
    int oldCount = 0;
    int expectedEmailCount = 1;
    // wait for the server to receive the messages
    waitForServerToReceiveEmails(expectedEmailCount);
    MimeMessage[] mma = greenMailServer.getReceivedMessages();
    assertNotNull(mma);
    assertEquals(expectedEmailCount, mma.length);
    MimeMessage mm = mma[oldCount];
    // http://jira.qos.ch/browse/LBCLASSIC-67
    assertEquals(subject, mm.getSubject());
    return (MimeMultipart) mm.getContent();
  }

  void waitUntilEmailIsSent() throws InterruptedException {
    loggerContext.getExecutorService().shutdown();
    loggerContext.getExecutorService().awaitTermination(1000, TimeUnit.MILLISECONDS);
  }

  @Test
  public void synchronousSmoke() throws Exception {
    String subject = "synchronousSmoke";
    buildSMTPAppender(subject, SYNCHRONOUS);

    smtpAppender.setLayout(buildPatternLayout(DEFAULT_PATTERN));
    smtpAppender.start();
    logger.addAppender(smtpAppender);
    logger.debug("hello");
    logger.error("en error", new Exception("an exception"));

    MimeMultipart mp = verifyAndExtractMimeMultipart(subject);
    String body = GreenMailUtil.getBody(mp.getBodyPart(0));
    assertTrue(body.startsWith(HEADER.trim()));
    assertTrue(body.endsWith(FOOTER.trim()));
  }

  @Test
  public void asynchronousSmoke() throws Exception {
    String subject = "asynchronousSmoke";
    buildSMTPAppender(subject, ASYNCHRONOUS);
    smtpAppender.setLayout(buildPatternLayout(DEFAULT_PATTERN));
    smtpAppender.start();
    logger.addAppender(smtpAppender);
    logger.debug("hello");
    logger.error("en error", new Exception("an exception"));

    waitUntilEmailIsSent();
    MimeMultipart mp = verifyAndExtractMimeMultipart(subject);
    String body = GreenMailUtil.getBody(mp.getBodyPart(0));
    assertTrue(body.startsWith(HEADER.trim()));
    assertTrue(body.endsWith(FOOTER.trim()));
  }

  // See also http://jira.qos.ch/browse/LOGBACK-734
  @Test
  public void callerDataShouldBeCorrectlySetWithAsynchronousSending() throws Exception {
    String subject = "LOGBACK-734";
    buildSMTPAppender("LOGBACK-734", ASYNCHRONOUS);
    smtpAppender.setLayout(buildPatternLayout(DEFAULT_PATTERN));
    smtpAppender.setIncludeCallerData(true);
    smtpAppender.start();
    logger.addAppender(smtpAppender);
    logger.debug("LOGBACK-734");
    logger.error("callerData", new Exception("ShouldBeCorrectlySetWithAsynchronousSending"));

    waitUntilEmailIsSent();
    MimeMultipart mp = verifyAndExtractMimeMultipart(subject);
    String body = GreenMailUtil.getBody(mp.getBodyPart(0));
    assertTrue(
        "actual [" + body + "]",
        body.contains("DEBUG " + this.getClass().getName() + " - LOGBACK-734"));
  }

  // lost MDC
  @Test
  public void LBCLASSIC_104() throws Exception {
    String subject = "LBCLASSIC_104";
    buildSMTPAppender(subject, SYNCHRONOUS);
    smtpAppender.setAsynchronousSending(false);
    smtpAppender.setLayout(buildPatternLayout(DEFAULT_PATTERN));
    smtpAppender.start();
    logger.addAppender(smtpAppender);
    MDC.put("key", "val");
    logger.debug("LBCLASSIC_104");
    MDC.clear();
    logger.error("en error", new Exception("test"));

    MimeMultipart mp = verifyAndExtractMimeMultipart(subject);
    String body = GreenMailUtil.getBody(mp.getBodyPart(0));
    assertTrue(body.startsWith(HEADER.trim()));
    System.out.println(body);
    assertTrue(body.contains("key=val"));
    assertTrue(body.endsWith(FOOTER.trim()));
  }

  @Test
  public void html() throws Exception {
    String subject = "html";
    buildSMTPAppender(subject, SYNCHRONOUS);
    smtpAppender.setAsynchronousSending(false);
    smtpAppender.setLayout(buildHTMLLayout());
    smtpAppender.start();
    logger.addAppender(smtpAppender);
    logger.debug("html");
    logger.error("en error", new Exception("an exception"));

    MimeMultipart mp = verifyAndExtractMimeMultipart(subject);

    // verifyAndExtractMimeMultipart strict adherence to xhtml1-strict.dtd
    SAXReader reader = new SAXReader();
    reader.setValidation(true);
    reader.setEntityResolver(new XHTMLEntityResolver());
    byte[] messageBytes = getAsByteArray(mp.getBodyPart(0).getInputStream());
    ByteArrayInputStream bais = new ByteArrayInputStream(messageBytes);
    try {
      reader.read(bais);
    } catch (DocumentException de) {
      System.out.println("incoming message:");
      System.out.println(new String(messageBytes));
      throw de;
    }
  }

  private byte[] getAsByteArray(InputStream inputStream) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    byte[] buffer = new byte[1024];
    int n = -1;
    while ((n = inputStream.read(buffer)) != -1) {
      baos.write(buffer, 0, n);
    }
    return baos.toByteArray();
  }

  private void configure(String file) throws JoranException {
    JoranConfigurator jc = new JoranConfigurator();
    jc.setContext(loggerContext);
    loggerContext.putProperty("port", "" + port);
    jc.doConfigure(file);
  }

  @Test
  public void testCustomEvaluator() throws Exception {
    configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "smtp/customEvaluator.xml");

    logger.debug("test");
    String msg2 = "CustomEvaluator";
    logger.debug(msg2);
    logger.debug("invisible");
    waitUntilEmailIsSent();
    MimeMultipart mp =
        verifyAndExtractMimeMultipart(
            "testCustomEvaluator " + this.getClass().getName() + " - " + msg2);
    String body = GreenMailUtil.getBody(mp.getBodyPart(0));
    assertEquals("testCustomEvaluator", body);
  }

  @Test
  public void testCustomBufferSize() throws Exception {
    configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "smtp/customBufferSize.xml");

    logger.debug("invisible1");
    logger.debug("invisible2");
    String msg = "hello";
    logger.error(msg);
    waitUntilEmailIsSent();
    MimeMultipart mp =
        verifyAndExtractMimeMultipart(
            "testCustomBufferSize " + this.getClass().getName() + " - " + msg);
    String body = GreenMailUtil.getBody(mp.getBodyPart(0));
    assertEquals(msg, body);
  }

  // this test fails intermittently on Jenkins.
  @Test
  public void testMultipleTo() throws Exception {
    buildSMTPAppender("testMultipleTo", SYNCHRONOUS);
    smtpAppender.setLayout(buildPatternLayout(DEFAULT_PATTERN));
    // buildSMTPAppender() already added one destination address
    smtpAppender.addTo("Test <*****@*****.**>, [email protected]");
    smtpAppender.start();
    logger.addAppender(smtpAppender);
    logger.debug("testMultipleTo hello");
    logger.error("testMultipleTo en error", new Exception("an exception"));
    Thread.yield();
    int expectedEmailCount = 3;
    waitForServerToReceiveEmails(expectedEmailCount);
    MimeMessage[] mma = greenMailServer.getReceivedMessages();
    assertNotNull(mma);
    assertEquals(expectedEmailCount, mma.length);
  }

  // http://jira.qos.ch/browse/LBCLASSIC-221
  @Test
  public void bufferShouldBeResetBetweenMessages() throws Exception {
    buildSMTPAppender("bufferShouldBeResetBetweenMessages", SYNCHRONOUS);
    smtpAppender.setLayout(buildPatternLayout(DEFAULT_PATTERN));
    smtpAppender.start();
    logger.addAppender(smtpAppender);
    String msg0 = "hello zero";
    logger.debug(msg0);
    logger.error("error zero");

    String msg1 = "hello one";
    logger.debug(msg1);
    logger.error("error one");

    Thread.yield();
    int oldCount = 0;
    int expectedEmailCount = oldCount + 2;
    waitForServerToReceiveEmails(expectedEmailCount);

    MimeMessage[] mma = greenMailServer.getReceivedMessages();
    assertNotNull(mma);
    assertEquals(expectedEmailCount, mma.length);

    MimeMessage mm0 = mma[oldCount];
    MimeMultipart content0 = (MimeMultipart) mm0.getContent();
    String body0 = GreenMailUtil.getBody(content0.getBodyPart(0));

    MimeMessage mm1 = mma[oldCount + 1];
    MimeMultipart content1 = (MimeMultipart) mm1.getContent();
    String body1 = GreenMailUtil.getBody(content1.getBodyPart(0));
    // second body should not contain content from first message
    assertFalse(body1.contains(msg0));
  }

  @Test
  public void multiLineSubjectTruncatedAtFirstNewLine() throws Exception {
    String line1 = "line 1 of subject";
    String subject = line1 + "\nline 2 of subject\n";
    buildSMTPAppender(subject, ASYNCHRONOUS);

    smtpAppender.setLayout(buildPatternLayout(DEFAULT_PATTERN));
    smtpAppender.start();
    logger.addAppender(smtpAppender);
    logger.debug("hello");
    logger.error("en error", new Exception("an exception"));

    Thread.yield();
    waitUntilEmailIsSent();
    waitForServerToReceiveEmails(1);

    MimeMessage[] mma = greenMailServer.getReceivedMessages();
    assertEquals(1, mma.length);
    assertEquals(line1, mma[0].getSubject());
  }
}
public class PatternLayoutTest extends AbstractPatternLayoutBaseTest<ILoggingEvent> {

  private PatternLayout pl = new PatternLayout();
  private LoggerContext lc = new LoggerContext();
  Logger logger = lc.getLogger(ConverterTest.class);
  Logger root = lc.getLogger(Logger.ROOT_LOGGER_NAME);

  ILoggingEvent le;
  List<String> optionList = new ArrayList<String>();

  public PatternLayoutTest() {
    super();
    Exception ex = new Exception("Bogus exception");
    le = makeLoggingEvent(ex);
  }

  @Before
  public void setUp() {
    pl.setContext(lc);
  }

  ILoggingEvent makeLoggingEvent(Exception ex) {
    return new LoggingEvent(
        ch.qos.logback.core.pattern.FormattingConverter.class.getName(),
        logger,
        Level.INFO,
        "Some message",
        ex,
        null);
  }

  @Override
  public ILoggingEvent getEventObject() {
    return makeLoggingEvent(null);
  }

  public PatternLayoutBase<ILoggingEvent> getPatternLayoutBase() {
    return new PatternLayout();
  }

  @Test
  public void testOK() {
    pl.setPattern("%d %le [%t] %lo{30} - %m%n");
    pl.start();
    String val = pl.doLayout(getEventObject());
    // 2006-02-01 22:38:06,212 INFO [main] c.q.l.pattern.ConverterTest - Some
    // message
    // 2010-12-29 19:04:26,137 INFO [pool-1-thread-47] c.q.l.c.pattern.ConverterTest - Some message
    String regex =
        ISO_REGEX + " INFO " + MAIN_REGEX + " c.q.l.c.pattern.ConverterTest - Some message\\s*";

    assertTrue("val=" + val, val.matches(regex));
  }

  @Test
  public void testNoExeptionHandler() {
    pl.setPattern("%m%n");
    pl.start();
    String val = pl.doLayout(le);
    assertTrue(val.contains("java.lang.Exception: Bogus exception"));
  }

  @Test
  public void testCompositePattern() {
    pl.setPattern("%-56(%d %lo{20}) - %m%n");
    pl.start();
    String val = pl.doLayout(getEventObject());
    // 2008-03-18 21:55:54,250 c.q.l.c.pattern.ConverterTest - Some message
    String regex = ISO_REGEX + " c.q.l.c.p.ConverterTest          - Some message\\s*";
    assertTrue(val.matches(regex));
  }

  @Test
  public void contextProperty() {
    pl.setPattern("%property{a}");
    pl.start();
    lc.putProperty("a", "b");

    String val = pl.doLayout(getEventObject());
    assertEquals("b", val);
  }

  @Test
  public void testNopExeptionHandler() {
    pl.setPattern("%nopex %m%n");
    pl.start();
    String val = pl.doLayout(le);
    assertTrue(!val.contains("java.lang.Exception: Bogus exception"));
  }

  @Test
  public void testWithParenthesis() {
    pl.setPattern("\\(%msg:%msg\\) %msg");
    pl.start();
    le = makeLoggingEvent(null);
    String val = pl.doLayout(le);
    // System.out.println("VAL == " + val);
    assertEquals("(Some message:Some message) Some message", val);
  }

  @Test
  public void testWithLettersComingFromLog4j() {
    // Letters: p = level and c = logger
    pl.setPattern("%d %p [%t] %c{30} - %m%n");
    pl.start();
    String val = pl.doLayout(getEventObject());
    // 2006-02-01 22:38:06,212 INFO [main] c.q.l.pattern.ConverterTest - Some
    // message
    String regex =
        ClassicTestConstants.ISO_REGEX
            + " INFO "
            + MAIN_REGEX
            + " c.q.l.c.pattern.ConverterTest - Some message\\s*";
    assertTrue(val.matches(regex));
  }

  @Test
  public void contextNameTest() {
    pl.setPattern("%contextName");
    lc.setName("aValue");
    pl.start();
    String val = pl.doLayout(getEventObject());
    assertEquals("aValue", val);
  }

  @Override
  public Context getContext() {
    return lc;
  }

  void configure(String file) throws JoranException {
    JoranConfigurator jc = new JoranConfigurator();
    jc.setContext(lc);
    jc.doConfigure(file);
  }

  @Test
  public void testConversionRuleSupportInPatternLayout() throws JoranException {
    configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "conversionRule/patternLayout0.xml");
    root.getAppender("LIST");
    String msg = "Simon says";
    logger.debug(msg);
    StringListAppender<ILoggingEvent> sla =
        (StringListAppender<ILoggingEvent>) root.getAppender("LIST");
    assertNotNull(sla);
    assertEquals(1, sla.strList.size());
    assertEquals(SampleConverter.SAMPLE_STR + " - " + msg, sla.strList.get(0));
  }

  @Test
  public void somekeReplace() {
    pl.setPattern("%replace(a1234b){'\\d{4}', 'XXXX'}");
    pl.start();
    StatusPrinter.print(lc);
    String val = pl.doLayout(getEventObject());
    assertEquals("aXXXXb", val);
  }

  @Test
  public void replaceWithJoran() throws JoranException {
    configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "pattern/replace0.xml");
    StatusPrinter.print(lc);
    root.getAppender("LIST");
    String msg = "And the number is 4111111111110000, expiring on 12/2010";
    logger.debug(msg);
    StringListAppender<ILoggingEvent> sla =
        (StringListAppender<ILoggingEvent>) root.getAppender("LIST");
    assertNotNull(sla);
    assertEquals(1, sla.strList.size());
    assertEquals("And the number is XXXX, expiring on 12/2010", sla.strList.get(0));
  }
}
public class ContextInitializerTest {

  LoggerContext loggerContext = new LoggerContext();
  Logger root = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME);

  @Before
  public void setUp() throws Exception {}

  @After
  public void tearDown() throws Exception {
    System.clearProperty(ContextInitializer.CONFIG_FILE_PROPERTY);
    System.clearProperty(ContextInitializer.STATUS_LISTENER_CLASS);
  }

  @Test
  @Ignore
  // this test works only if logback-test.xml or logback.xml files are on the classpath.
  // However, this is something we try to avoid in order to simplify the life
  // of users trying to follow the manual and logback-examples from an IDE
  public void reset() throws JoranException {
    {
      new ContextInitializer(loggerContext).autoConfig();
      Appender<ILoggingEvent> appender = root.getAppender("STDOUT");
      assertNotNull(appender);
      assertTrue(appender instanceof ConsoleAppender);
    }
    {
      loggerContext.stop();
      Appender<ILoggingEvent> appender = root.getAppender("STDOUT");
      assertNull(appender);
    }
  }

  @Test
  public void autoConfigFromSystemProperties() throws JoranException {
    doAutoConfigFromSystemProperties(ClassicTestConstants.INPUT_PREFIX + "autoConfig.xml");
    doAutoConfigFromSystemProperties("autoConfigAsResource.xml");
    // test passing a URL. note the relative path syntax with file:src/test/...
    doAutoConfigFromSystemProperties(
        "file:" + ClassicTestConstants.INPUT_PREFIX + "autoConfig.xml");
  }

  public void doAutoConfigFromSystemProperties(String val) throws JoranException {
    // lc.reset();
    System.setProperty(ContextInitializer.CONFIG_FILE_PROPERTY, val);
    new ContextInitializer(loggerContext).autoConfig();
    Appender<ILoggingEvent> appender = root.getAppender("AUTO_BY_SYSTEM_PROPERTY");
    assertNotNull(appender);
  }

  @Test
  public void autoStatusListener() throws JoranException {
    System.setProperty(
        ContextInitializer.STATUS_LISTENER_CLASS, TrivialStatusListener.class.getName());
    List<StatusListener> statusListenerList =
        loggerContext.getStatusManager().getCopyOfStatusListenerList();
    assertEquals(0, statusListenerList.size());
    doAutoConfigFromSystemProperties(ClassicTestConstants.INPUT_PREFIX + "autoConfig.xml");
    statusListenerList = loggerContext.getStatusManager().getCopyOfStatusListenerList();
    assertTrue(statusListenerList.size() + " should be 1", statusListenerList.size() == 1);
    // LOGBACK-767
    TrivialStatusListener tsl = (TrivialStatusListener) statusListenerList.get(0);
    assertTrue("expecting at least one event in list", tsl.list.size() > 0);
  }
}
Exemple #30
0
public class ConditionalTest {

  LoggerContext context = new LoggerContext();
  Logger root = context.getLogger(Logger.ROOT_LOGGER_NAME);

  int diff = RandomUtil.getPositiveInt();
  String randomOutputDir = CoreTestConstants.OUTPUT_DIR_PREFIX + diff + "/";

  @Before
  public void setUp() throws UnknownHostException {
    context.setName("c" + diff);
    context.putProperty("randomOutputDir", randomOutputDir);
  }

  @After
  public void tearDown() {
    StatusPrinter.printIfErrorsOccured(context);
  }

  void configure(String file) throws JoranException {
    JoranConfigurator jc = new JoranConfigurator();
    jc.setContext(context);
    jc.doConfigure(file);
  }

  @SuppressWarnings("rawtypes")
  @Test
  public void conditionalConsoleApp_IF_THEN_True()
      throws JoranException, IOException, InterruptedException {
    InetAddress localhost = InetAddress.getLocalHost();
    System.out.println(
        "In conditionalConsoleApp_IF_THEN_True, canonicalHostName=\""
            + localhost.getCanonicalHostName()
            + "] and hostNmae=\""
            + localhost.getHostName()
            + "\"");
    context.putProperty("aHost", localhost.getHostName());

    String configFileAsStr =
        ClassicTestConstants.JORAN_INPUT_PREFIX + "conditional/conditionalConsoleApp.xml";
    configure(configFileAsStr);
    FileAppender fileAppender = (FileAppender) root.getAppender("FILE");
    assertNotNull(fileAppender);

    ConsoleAppender consoleAppender = (ConsoleAppender) root.getAppender("CON");
    assertNotNull(consoleAppender);
    StatusChecker checker = new StatusChecker(context);
    checker.assertIsErrorFree();
  }

  @SuppressWarnings("rawtypes")
  @Test
  public void conditionalConsoleApp_IF_THEN_False()
      throws JoranException, IOException, InterruptedException {

    String configFileAsStr =
        ClassicTestConstants.JORAN_INPUT_PREFIX + "conditional/conditionalConsoleApp.xml";
    configure(configFileAsStr);
    FileAppender fileAppender = (FileAppender) root.getAppender("FILE");
    assertNotNull(fileAppender);

    ConsoleAppender consoleAppender = (ConsoleAppender) root.getAppender("CON");
    assertNull(consoleAppender);
    StatusChecker checker = new StatusChecker(context);
    checker.assertIsErrorFree();
  }

  @SuppressWarnings("rawtypes")
  @Test
  public void conditionalConsoleApp_IF_THEN_ELSE()
      throws JoranException, IOException, InterruptedException {

    String configFileAsStr =
        ClassicTestConstants.JORAN_INPUT_PREFIX + "conditional/conditionalConsoleApp_ELSE.xml";
    configure(configFileAsStr);

    FileAppender fileAppender = (FileAppender) root.getAppender("FILE");
    assertNotNull(fileAppender);

    ConsoleAppender consoleAppender = (ConsoleAppender) root.getAppender("CON");
    assertNull(consoleAppender);

    ListAppender listAppender = (ListAppender) root.getAppender("LIST");
    assertNotNull(listAppender);

    // StatusPrinter.printIfErrorsOccured(context);
    StatusChecker checker = new StatusChecker(context);
    checker.assertIsErrorFree();
  }

  @Test
  public void conditionalInclusionWithExistingFile()
      throws JoranException, IOException, InterruptedException {

    String configFileAsStr =
        ClassicTestConstants.JORAN_INPUT_PREFIX + "conditional/conditionalIncludeExistingFile.xml";
    configure(configFileAsStr);

    ConsoleAppender consoleAppender = (ConsoleAppender) root.getAppender("CON");
    assertNotNull(consoleAppender);
    StatusChecker checker = new StatusChecker(context);
    checker.assertIsErrorFree();
  }

  @Test
  public void conditionalInclusionWithInexistentFile()
      throws JoranException, IOException, InterruptedException {

    String configFileAsStr =
        ClassicTestConstants.JORAN_INPUT_PREFIX
            + "conditional/conditionalIncludeInexistentFile.xml";
    configure(configFileAsStr);

    ConsoleAppender consoleAppender = (ConsoleAppender) root.getAppender("CON");
    assertNull(consoleAppender);
    StatusChecker checker = new StatusChecker(context);
    checker.assertIsErrorFree();
  }
}