org.slf4j.LoggerFactory Java Examples

The following examples show how to use org.slf4j.LoggerFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MetricsConfiguration.java    From cubeai with Apache License 2.0 7 votes vote down vote up
@PostConstruct
public void init() {
    log.debug("Registering JVM gauges");
    metricRegistry.register(PROP_METRIC_REG_JVM_MEMORY, new MemoryUsageGaugeSet());
    metricRegistry.register(PROP_METRIC_REG_JVM_GARBAGE, new GarbageCollectorMetricSet());
    metricRegistry.register(PROP_METRIC_REG_JVM_THREADS, new ThreadStatesGaugeSet());
    metricRegistry.register(PROP_METRIC_REG_JVM_FILES, new FileDescriptorRatioGauge());
    metricRegistry.register(PROP_METRIC_REG_JVM_BUFFERS, new BufferPoolMetricSet(ManagementFactory.getPlatformMBeanServer()));
    metricRegistry.register(PROP_METRIC_REG_JVM_ATTRIBUTE_SET, new JvmAttributeGaugeSet());
    if (jHipsterProperties.getMetrics().getJmx().isEnabled()) {
        log.debug("Initializing Metrics JMX reporting");
        JmxReporter jmxReporter = JmxReporter.forRegistry(metricRegistry).build();
        jmxReporter.start();
    }
    if (jHipsterProperties.getMetrics().getLogs().isEnabled()) {
        log.info("Initializing Metrics Log reporting");
        Marker metricsMarker = MarkerFactory.getMarker("metrics");
        final Slf4jReporter reporter = Slf4jReporter.forRegistry(metricRegistry)
            .outputTo(LoggerFactory.getLogger("metrics"))
            .markWith(metricsMarker)
            .convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.MILLISECONDS)
            .build();
        reporter.start(jHipsterProperties.getMetrics().getLogs().getReportFrequency(), TimeUnit.SECONDS);
    }
}
 
Example #2
Source File: DiagnosticLogger.java    From synopsys-detect with Apache License 2.0 7 votes vote down vote up
private FileAppender<ILoggingEvent> addAppender(final String file) {
    final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    final PatternLayoutEncoder ple = new PatternLayoutEncoder();

    ple.setPattern("%date %level [%file:%line] %msg%n");
    ple.setContext(lc);
    ple.start();

    final FileAppender<ILoggingEvent> appender;
    appender = new FileAppender<>();
    appender.setFile(file);
    appender.setEncoder(ple);
    appender.setContext(lc);
    final ThresholdFilter levelFilter = new ThresholdFilter();
    levelFilter.setLevel(this.level.levelStr);
    levelFilter.start();
    appender.addFilter(levelFilter);

    appender.start();

    final ch.qos.logback.classic.Logger logbackLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
    logbackLogger.addAppender(appender);

    return appender;
}
 
Example #3
Source File: BaseRawKVStore.java    From sofa-jraft with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(final NodeExecutor nodeExecutor, final boolean isLeader, final KVStoreClosure closure) {
    final Timer.Context timeCtx = getTimeContext("EXECUTE");
    try {
        if (nodeExecutor != null) {
            nodeExecutor.execute(Status.OK(), isLeader);
        }
        setSuccess(closure, Boolean.TRUE);
    } catch (final Exception e) {
        final Logger LOG = LoggerFactory.getLogger(getClass());
        LOG.error("Fail to [EXECUTE], {}.", StackTraceUtil.stackTrace(e));
        if (nodeExecutor != null) {
            nodeExecutor.execute(new Status(RaftError.EIO, "Fail to [EXECUTE]"), isLeader);
        }
        setCriticalError(closure, "Fail to [EXECUTE]", e);
    } finally {
        timeCtx.stop();
    }
}
 
Example #4
Source File: WebContainerAccessLogAutoConfiguration.java    From spring-cloud-formula with Apache License 2.0 6 votes vote down vote up
private AccessLogHandler createAccessLogHandler(HttpHandler handler) {
    Logger logger = LoggerFactory.getLogger("accesslog");
    try {
        /*
        ref nginx log format:
        '$remote_addr - $remote_user [$time_local] "$request" '
              '$status $body_bytes_sent "$http_referer" '
              '"$http_user_agent" "$http_x_forwarded_for"';
         */
        AccessLogReceiver accessLogReceiver = logger::info;
        String formatString = "%h %l %u [%t] \"%r\" %s %b \"%{i,Referer}\""
                + " \"%{i,User-Agent}\" \"%{i,X-Forwarded-For}\" %D";
        return new AccessLogHandler(handler, accessLogReceiver, formatString,
                Undertow.class.getClassLoader());
    } catch (Exception ex) {
        throw new IllegalStateException("Failed to create AccessLogHandler", ex);
    }
}
 
Example #5
Source File: MetricsConfiguration.java    From cubeai with Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void init() {
    log.debug("Registering JVM gauges");
    metricRegistry.register(PROP_METRIC_REG_JVM_MEMORY, new MemoryUsageGaugeSet());
    metricRegistry.register(PROP_METRIC_REG_JVM_GARBAGE, new GarbageCollectorMetricSet());
    metricRegistry.register(PROP_METRIC_REG_JVM_THREADS, new ThreadStatesGaugeSet());
    metricRegistry.register(PROP_METRIC_REG_JVM_FILES, new FileDescriptorRatioGauge());
    metricRegistry.register(PROP_METRIC_REG_JVM_BUFFERS, new BufferPoolMetricSet(ManagementFactory.getPlatformMBeanServer()));
    metricRegistry.register(PROP_METRIC_REG_JVM_ATTRIBUTE_SET, new JvmAttributeGaugeSet());
    if (jHipsterProperties.getMetrics().getJmx().isEnabled()) {
        log.debug("Initializing Metrics JMX reporting");
        JmxReporter jmxReporter = JmxReporter.forRegistry(metricRegistry).build();
        jmxReporter.start();
    }
    if (jHipsterProperties.getMetrics().getLogs().isEnabled()) {
        log.info("Initializing Metrics Log reporting");
        Marker metricsMarker = MarkerFactory.getMarker("metrics");
        final Slf4jReporter reporter = Slf4jReporter.forRegistry(metricRegistry)
            .outputTo(LoggerFactory.getLogger("metrics"))
            .markWith(metricsMarker)
            .convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.MILLISECONDS)
            .build();
        reporter.start(jHipsterProperties.getMetrics().getLogs().getReportFrequency(), TimeUnit.SECONDS);
    }
}
 
Example #6
Source File: TestPlatformRuleContext.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
   super.setUp();
   
   placeId = UUID.randomUUID();
   address = Address.platformService(UUID.randomUUID(), RuleCapability.NAMESPACE, 1);
   
   context =
         PlatformRuleContext
            .builder()
            .withLogger(LoggerFactory.getLogger(TestPlatformRuleContext.class))
            .withModels(new RuleModelStore())
            .withPlatformBus(platformBus)
            .withEventLoop(eventLoop)
            .withPlaceId(placeId)
            .withSource(address)
            .withTimeZone(TimeZone.getDefault())
            .build();
}
 
Example #7
Source File: JsonHandlerExceptionResolver.java    From sca-best-practice with Apache License 2.0 6 votes vote down vote up
private ExceptionMetadata logException(Object handler, HttpServletRequest request, Exception exception) {
    ExceptionMetadata exceptionMetadata = new ExceptionMetadata();
    try {
        buildExceptionMetadata(exceptionMetadata, handler, request);
        if (exceptionMetadata.isHandlerMethod()) {
            Logger logger = LoggerFactory.getLogger(exceptionMetadata.getBeanType());
            logger.error("Error id is :" + exceptionMetadata.getErrorId());
            logger.error("RequestMapping is:");
            logger.error(exceptionMetadata.getRequestMapping());
            logger.error("HandlerMethod is:");
            logger.error(exceptionMetadata.getMethodName());
            logger.error("ParameterMap is:");
            logger.error(exceptionMetadata.getParameterMap(), exception);
        } else {
            log.error(handler + " execute failed, error id is:" + exceptionMetadata.getErrorId(), exception);
        }
    } catch (Exception e) {
        log.error(handler + " execute failed.", exception);
    }
    return exceptionMetadata;
}
 
Example #8
Source File: AnalyzerFactoryTestCase.java    From airsonic-advanced with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unused")
private List<String> toQueryTermString(String field, String str) {
    List<String> result = new ArrayList<>();
    try {
        TokenStream stream = analyzerFactory.getQueryAnalyzer().tokenStream(field,
                new StringReader(str));
        stream.reset();
        while (stream.incrementToken()) {
            result.add(stream.getAttribute(CharTermAttribute.class).toString()
                    .replaceAll("^term\\=", ""));
        }
        stream.close();
    } catch (IOException e) {
        LoggerFactory.getLogger(AnalyzerFactoryTestCase.class)
                .error("Error during Token processing.", e);
    }
    return result;
}
 
Example #9
Source File: TestOzoneManagerRatisServer.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * Test that all of {@link OzoneManagerProtocolProtos.Type} enum values are
 * categorized in {@link OmUtils#isReadOnly(OMRequest)}.
 */
@Test
public void testIsReadOnlyCapturesAllCmdTypeEnums() throws Exception {
  GenericTestUtils.LogCapturer logCapturer = GenericTestUtils.LogCapturer
      .captureLogs(LoggerFactory.getLogger(OmUtils.class));
  OzoneManagerProtocolProtos.Type[] cmdTypes =
      OzoneManagerProtocolProtos.Type.values();

  for (OzoneManagerProtocolProtos.Type cmdtype : cmdTypes) {
    OMRequest request = OMRequest.newBuilder()
        .setCmdType(cmdtype)
        .setClientId(clientId)
        .build();
    OmUtils.isReadOnly(request);
    assertFalse(cmdtype + " is not categorized in " +
            "OmUtils#isReadyOnly",
        logCapturer.getOutput().contains("CmdType " + cmdtype +" is not " +
            "categorized as readOnly or not."));
    logCapturer.clearOutput();
  }
}
 
Example #10
Source File: AnnotationUtils.java    From beihu-boot with Apache License 2.0 6 votes vote down vote up
/**
 * Handle the supplied annotation introspection exception.
 * it will simply be thrown, allowing it to propagate to the caller, and
 * nothing will be logged.
 * <p>Otherwise, this method logs an introspection failure (in particular
 * {@code TypeNotPresentExceptions}) before moving on, assuming nested
 * Class values were not resolvable within annotation attributes and
 * thereby effectively pretending there were no annotations on the specified
 * element.
 *
 * @param element the element that we tried to introspect annotations on
 * @param ex      the exception that we encountered
 * @see #rethrowAnnotationConfigurationException
 */
static void handleIntrospectionFailure(AnnotatedElement element, Throwable ex) {
    rethrowAnnotationConfigurationException(ex);

    Logger loggerToUse = logger;
    if (loggerToUse == null) {
        loggerToUse = LoggerFactory.getLogger(AnnotationUtils.class);
        logger = loggerToUse;
    }
    if (element instanceof Class && Annotation.class.isAssignableFrom((Class<?>) element)) {
        // Meta-annotation lookup on an annotation type
        if (loggerToUse.isDebugEnabled()) {
            loggerToUse.debug("Failed to introspect meta-annotations on [" + element + "]: " + ex);
        }
    } else {
        // Direct annotation lookup on regular Class, Method, Field
        if (loggerToUse.isInfoEnabled()) {
            loggerToUse.info("Failed to introspect annotations on [" + element + "]: " + ex);
        }
    }
}
 
Example #11
Source File: HtmlMakerFactory.java    From bitchat with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    int loopTimes = 200;

    class Runner implements Runnable {

        private Logger logger = LoggerFactory.getLogger(Runner.class);

        @Override
        public void run() {
            HtmlMakerFactory factory = HtmlMakerFactory.instance();
            logger.info("factory={},currentThread={}", (factory != null ? factory.getClass().getName() : "null"), Thread.currentThread().getName());
        }
    }

    for (int i = 0; i < loopTimes; i++) {
        new Thread(new Runner()).start();
    }
}
 
Example #12
Source File: MetricsConfiguration.java    From flair-registry with Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void init() {
    log.debug("Registering JVM gauges");
    metricRegistry.register(PROP_METRIC_REG_JVM_MEMORY, new MemoryUsageGaugeSet());
    metricRegistry.register(PROP_METRIC_REG_JVM_GARBAGE, new GarbageCollectorMetricSet());
    metricRegistry.register(PROP_METRIC_REG_JVM_THREADS, new ThreadStatesGaugeSet());
    metricRegistry.register(PROP_METRIC_REG_JVM_FILES, new FileDescriptorRatioGauge());
    metricRegistry.register(PROP_METRIC_REG_JVM_BUFFERS, new BufferPoolMetricSet(ManagementFactory.getPlatformMBeanServer()));
    if (jHipsterProperties.getMetrics().getJmx().isEnabled()) {
        log.debug("Initializing Metrics JMX reporting");
        JmxReporter jmxReporter = JmxReporter.forRegistry(metricRegistry).build();
        jmxReporter.start();
    }
    if (jHipsterProperties.getMetrics().getLogs().isEnabled()) {
        log.info("Initializing Metrics Log reporting");
        Marker metricsMarker = MarkerFactory.getMarker("metrics");
        final Slf4jReporter reporter = Slf4jReporter.forRegistry(metricRegistry)
            .outputTo(LoggerFactory.getLogger("metrics"))
            .markWith(metricsMarker)
            .convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.MILLISECONDS)
            .build();
        reporter.start(jHipsterProperties.getMetrics().getLogs().getReportFrequency(), TimeUnit.SECONDS);
    }
}
 
Example #13
Source File: MetricsConfiguration.java    From cubeai with Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void init() {
    log.debug("Registering JVM gauges");
    metricRegistry.register(PROP_METRIC_REG_JVM_MEMORY, new MemoryUsageGaugeSet());
    metricRegistry.register(PROP_METRIC_REG_JVM_GARBAGE, new GarbageCollectorMetricSet());
    metricRegistry.register(PROP_METRIC_REG_JVM_THREADS, new ThreadStatesGaugeSet());
    metricRegistry.register(PROP_METRIC_REG_JVM_FILES, new FileDescriptorRatioGauge());
    metricRegistry.register(PROP_METRIC_REG_JVM_BUFFERS, new BufferPoolMetricSet(ManagementFactory.getPlatformMBeanServer()));
    metricRegistry.register(PROP_METRIC_REG_JVM_ATTRIBUTE_SET, new JvmAttributeGaugeSet());
    if (jHipsterProperties.getMetrics().getJmx().isEnabled()) {
        log.debug("Initializing Metrics JMX reporting");
        JmxReporter jmxReporter = JmxReporter.forRegistry(metricRegistry).build();
        jmxReporter.start();
    }
    if (jHipsterProperties.getMetrics().getLogs().isEnabled()) {
        log.info("Initializing Metrics Log reporting");
        Marker metricsMarker = MarkerFactory.getMarker("metrics");
        final Slf4jReporter reporter = Slf4jReporter.forRegistry(metricRegistry)
            .outputTo(LoggerFactory.getLogger("metrics"))
            .markWith(metricsMarker)
            .convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.MILLISECONDS)
            .build();
        reporter.start(jHipsterProperties.getMetrics().getLogs().getReportFrequency(), TimeUnit.SECONDS);
    }
}
 
Example #14
Source File: LogBackConfiguration.java    From summerframework with Apache License 2.0 6 votes vote down vote up
@Override
public void init() {
    LoggerContext loggerContext = (LoggerContext)LoggerFactory.getILoggerFactory();
    if (loggerContext == null)
        return;
    List<Logger> loggerList = loggerContext.getLoggerList();
    ch.qos.logback.classic.Logger loggerKafka =
        loggerContext.getLogger("org.apache.kafka.clients.producer.ProducerConfig");
    if (loggerKafka != null) {
        loggerKafka.setLevel(ch.qos.logback.classic.Level.ERROR);
    }
    createBizLogger();
    for (Logger logger : loggerList) {
        AppenderAttachable appenderAttachable = logger;
        setLayout(loggerContext,appenderAttachable.iteratorForAppenders());
    }
}
 
Example #15
Source File: TestForEachActionTemplate.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Before
public void init(){
   this.context = new SimpleContext(UUID.randomUUID(), this.source, LoggerFactory.getLogger(TestForEachActionTemplate.class));
   
   SimpleModel model = new SimpleModel();
   model.setAttribute(Capability.ATTR_ID, modelAddress.toString());
   model.setAttribute(Capability.ATTR_TYPE, DeviceCapability.NAMESPACE);
   model.setAttribute(Capability.ATTR_ADDRESS, modelAddress.getRepresentation());
   context.putModel(model);

   logTemplate = new LogTemplate();
   logTemplate.setMessage(TemplatedValue.text("hello ${value}"));
   template = new ForEachModelTemplate(ImmutableSet.<String>of("address"));
   template.setActions(ImmutableList.of(logTemplate,logTemplate));
   template.setQuery(new TemplatedExpression(modelQuery));
   template.setVar("address");
}
 
Example #16
Source File: ConsumerActions.java    From apicurio-registry with Apache License 2.0 6 votes vote down vote up
/**
 * Dynamically remove given topic partition from the set of assigned topic partitions.
 *
 * @param tp topic partition to remove
 */
default CompletableFuture<Void> removeTopicParition(TopicPartition tp) {
    Objects.requireNonNull(tp);

    Logger log = LoggerFactory.getLogger(DynamicAssignment.class);
    log.info("Removing topic-partition: {}", tp);

    return submit(consumer -> {

        Set<TopicPartition> oldTps = consumer.assignment();
        Set<TopicPartition> newTps = new HashSet<>(oldTps);
        newTps.remove(tp);

        if (!oldTps.equals(newTps)) {
            log.info("Reassigning topic-partition(s): {} -> {}", oldTps, newTps);
            consumer.assign(newTps);
        }

        return null;
    });
}
 
Example #17
Source File: SolidotHotProcessor.java    From hot-crawler with MIT License 5 votes vote down vote up
@Override
@PostConstruct
protected void initialize(){
    RequestMethod requestMethod = RequestMethod.GET;
    setFieldsByProperties(siteProperties, requestMethod, generateHeader(),generateRequestBody());
    injectBeansByContext(context);
    setLog(LoggerFactory.getLogger(getClass()));
    this.elementClass = ITEM_KEY;
}
 
Example #18
Source File: XodusFileDataWriterLogLevelModificatorTest.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {

    context = (LoggerContext) LoggerFactory.getILoggerFactory();

    rootLogger = context.getLogger(Logger.ROOT_LOGGER_NAME);

    level = rootLogger.getLevel();
    rootLogger.setLevel(Level.DEBUG);
    context.addTurboFilter(new XodusFileDataWriterLogLevelModificator());
    context.getLogger("jetbrains.exodus").setLevel(Level.DEBUG);
}
 
Example #19
Source File: FsStateBackend.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
/**
 * Private constructor that creates a re-configured copy of the state backend.
 *
 * @param original The state backend to re-configure
 * @param configuration The configuration
 */
private FsStateBackend(FsStateBackend original, Configuration configuration, ClassLoader classLoader) {
	super(original.getCheckpointPath(), original.getSavepointPath(), configuration);

	// if asynchronous snapshots were configured, use that setting,
	// else check the configuration
	this.asynchronousSnapshots = original.asynchronousSnapshots.resolveUndefined(
			configuration.getBoolean(CheckpointingOptions.ASYNC_SNAPSHOTS));

	final int sizeThreshold = original.fileStateThreshold >= 0 ?
			original.fileStateThreshold :
			configuration.getInteger(CheckpointingOptions.FS_SMALL_FILE_THRESHOLD);

	if (sizeThreshold >= 0 && sizeThreshold <= MAX_FILE_STATE_THRESHOLD) {
		this.fileStateThreshold = sizeThreshold;
	}
	else {
		this.fileStateThreshold = CheckpointingOptions.FS_SMALL_FILE_THRESHOLD.defaultValue();

		// because this is the only place we (unlikely) ever log, we lazily
		// create the logger here
		LoggerFactory.getLogger(AbstractFileStateBackend.class).warn(
				"Ignoring invalid file size threshold value ({}): {} - using default value {} instead.",
				CheckpointingOptions.FS_SMALL_FILE_THRESHOLD.key(), sizeThreshold,
				CheckpointingOptions.FS_SMALL_FILE_THRESHOLD.defaultValue());
	}
}
 
Example #20
Source File: ConfigWatchTests.java    From spring-cloud-formula with Apache License 2.0 5 votes vote down vote up
@Test
public void watchWithExceptionAndWarnLog() {
    Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    root.setLevel(Level.WARN);
    ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);

    setupWatch(eventPublisher, "/app/", null);

    verify(eventPublisher, never()).publishEvent(ArgumentMatchers.any(RefreshEvent.class));
}
 
Example #21
Source File: ConfigurationFileProviderTest.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {

    MockitoAnnotations.initMocks(this);

    final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    logger.addAppender(mockAppender);

    final File hivemqHomefolder = folder.newFolder();
    confFolder = new File(hivemqHomefolder, "conf");
    assertTrue(confFolder.mkdir());

    when(systemInformation.getHiveMQHomeFolder()).thenReturn(hivemqHomefolder);
    when(systemInformation.getConfigFolder()).thenReturn(confFolder);
}
 
Example #22
Source File: RuleService.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private RuleContext createSimpleRuleContext(UUID placeId) {
   PlaceEnvironmentExecutor executor = registry.getExecutor(placeId).orNull();
   Collection<Model> models = executor != null ? 
         executor.getModelStore().getModels() : 
         modelDao.loadModelsByPlace(placeId, RuleModelStore.TRACKED_TYPES);

   // use a simple context just for resolving
   SimpleContext context = new SimpleContext(placeId, Address.platformService("rule"), LoggerFactory.getLogger("rules." + placeId));
   models.stream().filter((m) -> m != null).forEach((m) -> context.putModel(m));
   return context;
}
 
Example #23
Source File: XodusFileDataWriterLogLevelModificatorSingularityTest.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {

    context = (LoggerContext) LoggerFactory.getILoggerFactory();

    rootLogger = context.getLogger(Logger.ROOT_LOGGER_NAME);

    level = rootLogger.getLevel();
    rootLogger.setLevel(Level.DEBUG);
    context.addTurboFilter(new XodusFileDataWriterLogLevelModificator());
    context.getLogger("jetbrains.exodus").setLevel(Level.DEBUG);
}
 
Example #24
Source File: ITestApplication.java    From camel-spring-boot with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        try {
            overrideLoggingConfig();

            SpringApplication.run(ITestApplication.class, args);
        } catch (Throwable t) {
            LoggerFactory.getLogger(ITestApplication.class).error("Error while executing test", t);
            throw t;
        }
    }
 
Example #25
Source File: OnJarUnloadCompleted.java    From chaosblade-exec-jvm with Apache License 2.0 5 votes vote down vote up
/**
 * Close logback
 */
private void closeLogback() {
    try {
        ((LoggerContext)LoggerFactory.getILoggerFactory()).stop();
    } catch (Throwable cause) {
        cause.printStackTrace();
    }
}
 
Example #26
Source File: LogbackUtil.java    From summerframework with Apache License 2.0 5 votes vote down vote up
private static Logger buildInfoByLevel(String name, Level logLevel, String fileName) {
    RollingFileAppender appender = new AppenderBuild().getAppender(name, logLevel, fileName);
    LoggerContext context = (LoggerContext)LoggerFactory.getILoggerFactory();
    Logger logger = context.getLogger(name);

    logger.setAdditive(false);
    logger.addAppender(appender);
    return logger;
}
 
Example #27
Source File: ClosureShardingAlgorithm.java    From sharding-jdbc-1.5.1 with Apache License 2.0 5 votes vote down vote up
public ClosureShardingAlgorithm(final String expression, final String logRoot) {
    Preconditions.checkArgument(!Strings.isNullOrEmpty(expression));
    Preconditions.checkArgument(!Strings.isNullOrEmpty(logRoot));
    Binding binding = new Binding();
    binding.setVariable("log", LoggerFactory.getLogger(Joiner.on(".").join("com.dangdang.ddframe.rdb.sharding.configFile", logRoot.trim())));
    closureTemplate = (Closure) new GroovyShell(binding).evaluate(Joiner.on("").join("{it -> \"", expression.trim(), "\"}"));
}
 
Example #28
Source File: IrisStdioHijack.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private void hijackStdio() {
   Logger stdoutLogger = LoggerFactory.getLogger("stdout");
   Logger stderrLogger = LoggerFactory.getLogger("stderr");

   PrintStream newOut = new PrintStream(new StdioOutputStream(stdoutLogger));
   PrintStream newErr = new PrintStream(new StdioOutputStream(stderrLogger));

   System.setOut(newOut);
   System.setErr(newErr);
}
 
Example #29
Source File: TestOverrideNamespaceContext.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
   delegate = new SimpleContext(UUID.randomUUID(), Address.platformService(UUID.randomUUID(), "rule"), LoggerFactory.getLogger(TestThresholdTrigger.class));
   delegate.setVariable("_baseVar", "basevalue");
   delegate.clearDirty();
   context1 = new NamespaceContext("context1", delegate);
   context2 = new NamespaceContext("context2", delegate);
}
 
Example #30
Source File: LogsResource.java    From cubeai with Apache License 2.0 5 votes vote down vote up
@GetMapping("/logs")
@Timed
public List<LoggerVM> getList() {
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    return context.getLoggerList()
        .stream()
        .map(LoggerVM::new)
        .collect(Collectors.toList());
}