Java ch.qos.logback.core.AppenderBase 代码实例

・18 分钟阅读

以下是展示如何使用ch.qos.logback.core.AppenderBase的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


public void assertLogContent(LogContentAssertion logContentAssertion) {
    final ArrayList<MessageAndLogLevel> log = new ArrayList<MessageAndLogLevel>();
    Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    AppenderBase<ILoggingEvent> appender = new AppenderBase<ILoggingEvent>() {
        @Override
        protected void append(ILoggingEvent event) {
            log.add(new MessageAndLogLevel(event.getFormattedMessage(), event.getLevel()));
        }
    };
    appender.start();
    root.addAppender(appender);
    logContentAssertion.executeLogCreatingAction();
    logContentAssertion.assertLogContent(log);
    root.detachAppender(appender);
}
 

实例 2


@Test
public void testDeprecatedKeys() {
  // Add a log appender to intercept logs from the Configuration object
  ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();
  final AtomicBoolean logMessageReceived = new AtomicBoolean(false);
  if (loggerFactory instanceof LoggerContext) {
    LoggerContext loggerContext = (LoggerContext) loggerFactory;
    AppenderBase<ILoggingEvent> appender = new AppenderBase<ILoggingEvent>() {
      @Override
      protected void append(ILoggingEvent eventObject) {
        logMessageReceived.set(true);
      }
    };
    loggerContext.getLogger(Configuration.class).addAppender(appender);
    appender.setContext(loggerContext);
    appender.start();
  }
  // Dump the configuration as json
  StringBuilder builder = new StringBuilder();
  ConfigurationJsonTool.exportToJson(SConfiguration.create(), builder);
  String address = new Gson().fromJson(builder.toString(), JsonObject.class)
    .get("security.auth.server.bind.address").getAsString();
  Assert.assertEquals("0.0.0.0", address);
  // There shouldn't be any log message, even we access the deprecated key
  Assert.assertFalse(logMessageReceived.get());
  // If we access the deprecated key directly, there should still be deprecated key warning.
  // That's because the log level shouldn't been reset.
  SConfiguration.create().get("security.auth.server.bind.address");
  Assert.assertTrue(logMessageReceived.get());
}
 

实例 3


@Test
public void validateVerbosePrintHelp() {
    // Assemble
    final String[] helpArgs = {"-help", "-verbose"};
    final List<ILoggingEvent> loggingEventList = new ArrayList<ILoggingEvent>();
    final AppenderBase<ILoggingEvent> appenderBase = new AppenderBase<ILoggingEvent>() {
        @Override
        protected void append(ILoggingEvent eventObject) {
            loggingEventList.add(eventObject);
        }
    };
    addAppenderToLogger(AbstractApplicationLauncher.class.getName(), appenderBase);
    final MockApplication unitUnderTest = new MockApplication(description, helpArgs, version);
    // Act
    unitUnderTest.execute();
    // Assert
    final List<String> callTrace = unitUnderTest.callTrace;
    Assert.assertEquals(0, callTrace.size());
    Assert.assertEquals(2, loggingEventList.size());
    Assert.assertTrue(loggingEventList.get(1).getMessage().contains("Help printed."));
}
 

实例 4


@Test
public void validateHelpPrintedOnApplicationException() {
    // Assemble
    final String exceptionMessage = "The Foo was not a Bar";
    final String[] helpArgs = {"-verbose", "foo"};
    final List<ILoggingEvent> loggingEventList = new ArrayList<ILoggingEvent>();
    final AppenderBase<ILoggingEvent> appenderBase = new AppenderBase<ILoggingEvent>() {
        @Override
        protected void append(ILoggingEvent eventObject) {
            loggingEventList.add(eventObject);
        }
    };
    addAppenderToLogger(AbstractApplicationLauncher.class.getName(), appenderBase);
    final MockApplication unitUnderTest = new MockApplication(description, helpArgs, version);
    unitUnderTest.exceptionMessageOnApplicationRun = exceptionMessage;
    // Act
    unitUnderTest.execute();
    // Assert
    Assert.assertTrue(loggingEventList.get(1).getMessage().contains(exceptionMessage));
}
 

实例 5


private void addAppenderToLogger(final String name, final AppenderBase<ILoggingEvent> appender) {
        boolean added = false;
        // Lower the logging squelch for all relevant Appenders to DEBUG
        final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
        for (ch.qos.logback.classic.Logger current : context.getLoggerList()) {
            if (current.getName().equalsIgnoreCase(name)) {
                current.addAppender(appender);
                appender.start();
                added = true;
            }
        }
        if (!added) {
            throw new IllegalStateException("Appender not added to Logger [" + name + "].");
        }
    }
 

实例 6


@Before
public void setupLogger() {
    final Logger logger = getLogger();
    oldLogLevel = logger.getLevel();
    logger.setLevel(Level.ALL);
    final AppenderBase<ILoggingEvent> appender = new AppenderBase<ILoggingEvent>() {
        @Override
        protected void append(final ILoggingEvent eventObject) {
            logStatements.add(eventObject);
        }
    };
    logger.addAppender(appender);
    appender.start();
}
 

实例 7


public void notifySelected() {
        if (loggerContext == null) {
                while (loggerContext == null) {
                        ILoggerFactory lf = LoggerFactory.getILoggerFactory();
                        if (lf instanceof LoggerContext) {
                                loggerContext = (LoggerContext) lf;
                        } 
                        else {
                                try {
                                        Thread.sleep(100);
                                } catch (Exception ex) {
                                }
                        }
                }
                traceAppender = new AppenderBase<ILoggingEvent>() {
                        //
                        private int currentIndentLevel = 0;
                        //
                        @Override
                        protected void append(ILoggingEvent eventObject) {
                                String msg = eventObject.getFormattedMessage();
                                Object[] args = eventObject.getArgumentArray();
                                // Suffix the profiler information to the message
                                // if available.
                                String profileString = "";
                                Long profileInfo = LogX.getProfileInfo(eventObject.getLoggerName());
                                if (profileInfo != null) {
                                        profileString = "[" + profileInfo/1000000 + "ms";
                                        Long rootProfileInfo = LogX.getRootProfileInfo(eventObject.getLoggerName());
                                        if (null != rootProfileInfo) {
                                                profileString += ", " + (rootProfileInfo / 1000000) + "ms total";
                                        }
                                        profileString += "] ";
                                }
                                String outputMsg = null;
                                if (msg != null && !msg.equals("") && BaseTreeUtilAppender.outputFormattedMessage(msg, args)) {
                                        outputMsg = profileString + msg;
                                }
                                int indentLevel = LogX.getTraceLevel(eventObject.getLoggerName());
                                while (currentIndentLevel < indentLevel) {
                                        if (currentIndentLevel == (indentLevel-1)) {
                                                if (outputMsg != null) {
                                                        addTrace(outputMsg);
                                                        outputMsg = null; // indicates already output
                                                }
                                                else {
                                                        addTrace(">>");
                                                }
                                        }
                                        else {
                                                addTrace(">>");
                                        }
                                        startTraceLevel();
                                        currentIndentLevel++;
                                }
                                while (currentIndentLevel > indentLevel) {
                                        endTraceLevel();
                                        currentIndentLevel--;
                                }
                                if (outputMsg != null) {
                                        addTrace(outputMsg);
                                }
                                if (args != null) {
                                        for (Object arg : args) {
                                                addTrace(arg);
                                        }
                                }
                        }
                };
                traceAppender.addFilter(new RewriterLoggingNamedRewriterFilter());
                traceAppender.setContext(loggerContext);
                loggerContext.getLogger(Trace.getDefaultLoggerName()).addAppender(traceAppender);
        }
        traceAppender.start();
}
 

实例 8


private void setupLogging() {
        // Set up the relevant trace and query information
        // specific for this query.
        RewriterLogging.setUUID(queryUUID);
        traceAppender = new AppenderBase<ILoggingEvent>() {
                @Override
                protected void append(ILoggingEvent eventObject) {
                        int      level           = LogX.getTraceLevel(eventObject.getLoggerName());
                        Long     rootProfileInfo = LogX.getRootProfileInfo(eventObject.getLoggerName());
                        Long     profileInfo     = LogX.getProfileInfo(eventObject.getLoggerName());
                        Marker   marker          = eventObject.getMarker();
                        String   msg             = eventObject.getFormattedMessage();
                        Object[] args            = eventObject.getArgumentArray(); 
                        for (TraceListener traceListener : traceListeners) {
                                traceListener.traceEvent(queryUUID, level, rootProfileInfo, profileInfo, marker, msg, args);
                        }
                        if (RewriterLogging.REWRITER_PROFILE_INFO.equals(eventObject.getMarker())) {
                                if (profileInfo != null) {
                                        String rewriterName = RewriterLogging.getCurrentRewriterName();
                                        Long currentProfileInfo = rewriterProfiledTimes.get(rewriterName);
                                        if (currentProfileInfo != null) {
                                                currentProfileInfo += profileInfo;
                                        } 
                                        else {
                                                currentProfileInfo = profileInfo;
                                        }
                                        rewriterProfiledTimes.put(rewriterName, currentProfileInfo);
                                }
                        }
                }
        };
        traceAppender.addFilter(new RewriterLoggingNamedRewriterFilter());
        traceAppender.setContext(_loggerContext);
        justificationAppender = new AppenderBase<ILoggingEvent>() {
                @Override
                protected void append(ILoggingEvent eventObject) {
                        int      level       = LogX.getTraceLevel(eventObject.getLoggerName());
                        Marker   marker      = eventObject.getMarker();
                        String   msg         = eventObject.getFormattedMessage();
                        Object[] args        = eventObject.getArgumentArray(); 
                        for (JustificationListener justificationListener : justificationListeners) {
                                justificationListener.justificationEvent(queryUUID, level, marker, msg, args);
                        }
                }
        };
        justificationAppender.addFilter(new RewriterLoggingNamedRewriterFilter());
        justificationAppender.setContext(_loggerContext);
        queryUUIDFilter = new Filter<ILoggingEvent>() {
                @Override
                public FilterReply decide(ILoggingEvent event) {
                        String eventUUID = event.getMDCPropertyMap().get(RewriterLogging.getMDCUUIDKey());
                        if (queryUUID.equals(eventUUID)) {
                                if (!options.isTraceOn() &&
                                        event.getLoggerName().equals("com.sri.ai.grinder.helper.Trace")) {
                                        return FilterReply.DENY;
                                }
                                if (!options.isJustificationsOn() &&
                                        event.getLoggerName().equals("com.sri.ai.grinder.helper.Justification")) {
                                        return FilterReply.DENY;
                                }
                                return FilterReply.ACCEPT;
                        }
                        return FilterReply.DENY;
                }
        };
        queryUUIDFilter.setContext(_loggerContext);
        traceAppender.addFilter(queryUUIDFilter);
        justificationAppender.addFilter(queryUUIDFilter);
        queryUUIDFilter.start();
        traceAppender.start();
        justificationAppender.start();
        _loggerContext.getLogger(Trace.getDefaultLoggerName()).addAppender(traceAppender);
        _loggerContext.getLogger(Justification.getDefaultLoggerName()).addAppender(justificationAppender);
}
 
讨论
淘淘あ西西 profile image