org.slf4j.bridge.SLF4JBridgeHandler Java Examples

The following examples show how to use org.slf4j.bridge.SLF4JBridgeHandler. 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: GossipLogModule.java    From gossip with MIT License 6 votes vote down vote up
private void initializeLogback() {
    Path logbackFilePath = Paths.get(configPath, "logback.xml");
    if (logbackFilePath.toFile().exists()) {
        try {
            // Load logback configuration
            LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
            context.reset();
            JoranConfigurator configurator = new JoranConfigurator();
            configurator.setContext(context);
            configurator.doConfigure(logbackFilePath.toFile());

            // Install java.util.logging bridge
            SLF4JBridgeHandler.removeHandlersForRootLogger();
            SLF4JBridgeHandler.install();
        } catch (JoranException e) {
            throw new GossipInitializeException("Misconfiguration on logback.xml, check it.", e);
        }
    }
}
 
Example #2
Source File: RequestParameterPolicyEnforcementFilterTests.java    From cas-server-security-filter with Apache License 2.0 6 votes vote down vote up
@Test
public void configureSlf4jLogging() throws ServletException {
    final RequestParameterPolicyEnforcementFilter filter = new RequestParameterPolicyEnforcementFilter();

    // mock up filter config.
    final Set<String> initParameterNames = new HashSet<String>();

    initParameterNames.add(RequestParameterPolicyEnforcementFilter.CHARACTERS_TO_FORBID);
    initParameterNames.add(AbstractSecurityFilter.LOGGER_HANDLER_CLASS_NAME);
    final Enumeration parameterNamesEnumeration = Collections.enumeration(initParameterNames);
    final FilterConfig filterConfig = mock(FilterConfig.class);
    when(filterConfig.getInitParameterNames()).thenReturn(parameterNamesEnumeration);

    when(filterConfig.getInitParameter(RequestParameterPolicyEnforcementFilter.CHARACTERS_TO_FORBID))
            .thenReturn("none");
    when(filterConfig.getInitParameter(RequestParameterPolicyEnforcementFilter.PARAMETERS_TO_CHECK))
            .thenReturn(null);
    when(filterConfig.getInitParameter(AbstractSecurityFilter.LOGGER_HANDLER_CLASS_NAME))
            .thenReturn(SLF4JBridgeHandler.class.getCanonicalName());

    filter.init(filterConfig);
    assertTrue(filter.getLogger().getHandlers().length > 0);
    assertTrue(filter.getLogger().getHandlers()[0] instanceof SLF4JBridgeHandler);
}
 
Example #3
Source File: ServerTest.java    From raml-tester with Apache License 2.0 6 votes vote down vote up
@Before
public void initImpl() throws LifecycleException, ServletException {
    if (!inited.contains(getClass())) {
        inited.add(getClass());
        SLF4JBridgeHandler.removeHandlersForRootLogger();
        SLF4JBridgeHandler.install();

        tomcat = new Tomcat();
        tomcat.setPort(PORT);
        tomcat.setBaseDir(".");
        final Context ctx = tomcat.addWebapp("", "src/test");
        ctx.setJarScanner(NO_SCAN);
        ((Host) ctx.getParent()).setAppBase("");

        init(ctx);

        tomcat.start();
    }
}
 
Example #4
Source File: Main.java    From jbake with MIT License 6 votes vote down vote up
protected void run(String[] args) {
    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();
    LaunchOptions res = parseArguments(args);

    final JBakeConfiguration config;
    try {
        if (res.isRunServer()) {
            config = getJBakeConfigurationFactory().createJettyJbakeConfiguration(res.getSource(), res.getDestination(), res.isClearCache());
        } else {
            config = getJBakeConfigurationFactory().createDefaultJbakeConfiguration(res.getSource(), res.getDestination(), res.isClearCache());
        }
    } catch (final ConfigurationException e) {
        throw new JBakeException("Configuration error: " + e.getMessage(), e);
    }
    run(res, config);
}
 
Example #5
Source File: Util.java    From tessera with Apache License 2.0 6 votes vote down vote up
public static JerseyTest create(Enclave enclave) {

        SLF4JBridgeHandler.removeHandlersForRootLogger();
        SLF4JBridgeHandler.install();

        return new JerseyTest() {
            @Override
            protected Application configure() {
                
                enable(TestProperties.LOG_TRAFFIC);
                enable(TestProperties.DUMP_ENTITY);
                set(TestProperties.CONTAINER_PORT, SocketUtils.findAvailableTcpPort());
                EnclaveApplication application = new EnclaveApplication(new EnclaveResource(enclave));

                ResourceConfig config = ResourceConfig.forApplication(application);
                config.packages("com.quorum.tessera.enclave.rest");
                return config;
            }

        };
    }
 
Example #6
Source File: CentralModule.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@EnsuresNonNull("startupLogger")
@SuppressWarnings("contracts.postcondition.not.satisfied")
private static void initLogging(File confDir, File logDir) {
    File logbackXmlOverride = new File(confDir, "logback.xml");
    if (logbackXmlOverride.exists()) {
        System.setProperty("logback.configurationFile", logbackXmlOverride.getAbsolutePath());
    }
    String prior = System.getProperty("glowroot.log.dir");
    System.setProperty("glowroot.log.dir", logDir.getPath());
    try {
        startupLogger = LoggerFactory.getLogger("org.glowroot");
    } finally {
        System.clearProperty("logback.configurationFile");
        if (prior == null) {
            System.clearProperty("glowroot.log.dir");
        } else {
            System.setProperty("glowroot.log.dir", prior);
        }
    }
    // install jul-to-slf4j bridge for guava/grpc/protobuf which log to jul
    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();
}
 
Example #7
Source File: StructuredLogging.java    From flo with Apache License 2.0 6 votes vote down vote up
public static void configureStructuredLogging(Level level) {
  final Logger rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);

  final LoggerContext context = rootLogger.getLoggerContext();
  context.reset();

  final StructuredLoggingEncoder encoder = new StructuredLoggingEncoder();
  encoder.start();

  final ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<ILoggingEvent>();
  appender.setTarget("System.err");
  appender.setName("stderr");
  appender.setEncoder(encoder);
  appender.setContext(context);
  appender.start();

  rootLogger.addAppender(appender);
  rootLogger.setLevel(fromLocationAwareLoggerInteger(level.toInt()));

  SLF4JBridgeHandler.install();
}
 
Example #8
Source File: LOGBackConfigurer.java    From styx with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize LOGBack from the given URL.
 *
 * @param url              the url pointing to the location of the config file.
 * @param installJULBridge set to true to install SLF4J JUL bridge
 * @throws IllegalArgumentException if the url points to a non existing location or an error occurs during the parsing operation.
 */
public static void initLogging(URL url, boolean installJULBridge) {
    StaticLoggerBinder.getSingleton();
    ContextSelector selector = ContextSelectorStaticBinder.getSingleton().getContextSelector();
    LoggerContext loggerContext = selector.getLoggerContext();
    loggerContext.stop();
    ContextInitializer ctxi = new ContextInitializer(loggerContext);
    try {
        ctxi.configureByResource(url);
        loggerContext.start();
        if (installJULBridge) {
            //uninstall already present handlers we want to
            //continue logging through SLF4J after this point
            Logger l = LogManager.getLogManager().getLogger("");
            for (Handler h : l.getHandlers()) {
                l.removeHandler(h);
            }
            SLF4JBridgeHandler.install();

        }
    } catch (JoranException e) {
        throw new IllegalArgumentException("exception while initializing LOGBack", e);
    }
}
 
Example #9
Source File: JULBridge.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
public static void configure() {
  // Route JUL logging messages to SLF4J.
  LogManager.getLogManager().reset();
  SLF4JBridgeHandler.removeHandlersForRootLogger();
  SLF4JBridgeHandler.install();

  // Parquet installs a default handler if none found, so remove existing handlers and add slf4j
  // one.
  // Also add slf4j bridge handle and configure additivity to false so that log messages are not
  // printed out twice
  final Handler[] handlers = PARQUET_ROOT_LOGGER.getHandlers();
  for(int i = 0; i < handlers.length; i++) {
    PARQUET_ROOT_LOGGER.removeHandler(handlers[i]);
  }
  PARQUET_ROOT_LOGGER.addHandler(new SLF4JBridgeHandler());
  PARQUET_ROOT_LOGGER.setUseParentHandlers(false);
}
 
Example #10
Source File: JavaUtilLoggingConfigurer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void configure(LogLevel logLevel) {
    if (configured) {
        return;
    }

    LogManager.getLogManager().reset();
    SLF4JBridgeHandler.install();
    Logger.getLogger("").setLevel(java.util.logging.Level.FINE);
    configured = true;
}
 
Example #11
Source File: CitizenIntelligenceAgencyServer.java    From cia with Apache License 2.0 5 votes vote down vote up
/**
 * Inits the logger.
 */
private static void initLogger() {
	System.setProperty("logback.configurationFile", "src/main/resources/logback.xml");
	System.setProperty("slf4j", "true");
	System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.Slf4jLog");
	// System.setProperty("javax.net.debug", "all");

	LogManager.getLogManager().reset();
	SLF4JBridgeHandler.install();
	java.util.logging.Logger.getLogger("global").setLevel(Level.FINEST);
}
 
Example #12
Source File: LoggingConfiguratorTest.java    From selenium-grid-extensions with Apache License 2.0 5 votes vote down vote up
@After
public void tearDown() throws Exception {
    // restore
    Logger.getRootLogger().removeAllAppenders();
    for (Appender appender : appenders) {
        Logger.getRootLogger().addAppender(appender);
    }

    SLF4JBridgeHandler.uninstall();
}
 
Example #13
Source File: PackageTest.java    From jqm with Apache License 2.0 5 votes vote down vote up
@Test(expected = NoResolvedResultException.class)
public void testFailingDependency() throws Exception
{
    jqmlogger.debug("**********************************************************");
    jqmlogger.debug("Starting test testFailingDependency");

    SLF4JBridgeHandler.install();

    Maven.configureResolver()
            .withRemoteRepo(MavenRemoteRepositories.createRemoteRepository("marsu", "http://marsupilami.com", "default"))
            .withMavenCentralRepo(false).resolve("com.enioka.jqm:marsu:1.1.4").withTransitivity().asFile();
}
 
Example #14
Source File: AppInitializer.java    From oxTrust with MIT License 5 votes vote down vote up
@PostConstruct
public void createApplicationComponents() {
	SecurityProviderUtility.installBCProvider();

	// Remove JUL console logger
	SLF4JBridgeHandler.removeHandlersForRootLogger();

	// Add SLF4JBridgeHandler to JUL root logger
	SLF4JBridgeHandler.install();
}
 
Example #15
Source File: AutodetectLogManager.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
private AutodetectLogManager() {
    if (isLogbackInUse()) {
        logManager = new LogbackLogManager();
    } else {
        logManager = new NoOpLogManager();
    }

    try {
        java.util.logging.LogManager.getLogManager().reset();
        SLF4JBridgeHandler.removeHandlersForRootLogger();
        SLF4JBridgeHandler.install();
    } catch (Exception e) {
        System.err.println("Unable to install JUL to SLF4J bridge");
    }
}
 
Example #16
Source File: ServiceMain.java    From helios with Apache License 2.0 5 votes vote down vote up
protected static void setupLogging(LoggingConfig config, String sentryDsn) {
  if (config.getNoLogSetup()) {
    return;
  }

  // Hijack JUL
  SLF4JBridgeHandler.removeHandlersForRootLogger();
  SLF4JBridgeHandler.install();

  final int verbose = config.getVerbosity();
  final Level level = get(asList(INFO, DEBUG, ALL), verbose, ALL);
  final File logconfig = config.getConfigFile();

  if (logconfig != null) {
    LoggingConfigurator.configure(logconfig);
  } else {
    if (config.isSyslog()) {
      LoggingConfigurator.configureSyslogDefaults("helios", level);
    } else {
      LoggingConfigurator.configureDefaults("helios", level);
    }

    if (!Strings.isNullOrEmpty(sentryDsn)) {
      LoggingConfigurator.addSentryAppender(sentryDsn);
    }
  }
}
 
Example #17
Source File: AbstractPitMojo.java    From pitest with Apache License 2.0 5 votes vote down vote up
private void switchLogging() {
  if (this.useSlf4j) {
    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();
    Logger.getLogger("PIT").addHandler(new SLF4JBridgeHandler());
    SysOutOverSLF4J.sendSystemOutAndErrToSLF4J();
  }
}
 
Example #18
Source File: JulBridge.java    From xio with Apache License 2.0 5 votes vote down vote up
public static synchronized void initialize() {
  if (dummy == -1) {
    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();
    dummy = 0;
  }
}
 
Example #19
Source File: ClusterLab.java    From OSPREY3 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args)
throws Exception {

	// configure logging
	SLF4JBridgeHandler.removeHandlersForRootLogger();
	SLF4JBridgeHandler.install();

	//forkCluster();
	//multiProcessCluster(args);
	slurmCluster();
}
 
Example #20
Source File: Atlas.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
private static void installLogBridge() {
    // Optionally remove existing handlers attached to j.u.l root logger
    SLF4JBridgeHandler.removeHandlersForRootLogger();  // (since SLF4J 1.6.5)

    // add SLF4JBridgeHandler to j.u.l's root logger, should be done once during
    // the initialization phase of your application
    SLF4JBridgeHandler.install();
}
 
Example #21
Source File: BaleenLogging.java    From baleen with Apache License 2.0 5 votes vote down vote up
/**
 * Configure logging based on a list of builders provided to it. Injects the configured logging to
 * replace the default UIMA loggers, and also sets up metrics on the logging.
 *
 * @param builders The builders to use to configure the logging
 */
public void configure(List<BaleenLoggerBuilder> builders) {
  // Install JUL to SLF4J handling (JUL is default for UIMA)
  SLF4JBridgeHandler.removeHandlersForRootLogger();
  SLF4JBridgeHandler.install();

  // Configure Logback
  LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
  Logger rootLogger = context.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);

  // Install the level change propagator to reduce the impact of JUL logging
  context.addListener(new LevelChangePropagator());

  // Remove all the existing appenders
  rootLogger.detachAndStopAllAppenders();

  for (BaleenLoggerBuilder builder : builders) {
    PatternLayoutEncoder ple = new PatternLayoutEncoder();
    ple.setCharset(StandardCharsets.UTF_8);
    ple.setContext(context);
    ple.setPattern(builder.getPattern());
    ple.start();

    Appender<ILoggingEvent> appender = builder.build(context, ple);
    if (!appender.isStarted()) {
      appender.start();
    }

    rootLogger.addAppender(appender);
  }

  LOGGER.debug("Adding instrumented metrics for logging");
  // Add an instrumented appender so we get the information about logging
  // through metrics
  InstrumentedAppender instrumentedAppender =
      new InstrumentedAppender(MetricsFactory.getInstance().getRegistry());
  instrumentedAppender.setContext(context);
  instrumentedAppender.start();
  rootLogger.addAppender(instrumentedAppender);
}
 
Example #22
Source File: GraviteeApisContainer.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@Override
protected void initializeLogging() {
    super.initializeLogging();
    
    // Move all java util logging logs to SLF4j
    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();
}
 
Example #23
Source File: JerseyUseSlf4jPlease.java    From json-schema-validator-demo with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void contextInitialized(final ServletContextEvent sce)
{
    final Logger rootLogger = LogManager.getLogManager().getLogger("");
    for (final Handler handler : rootLogger.getHandlers()) {
        rootLogger.removeHandler(handler);
    }
    SLF4JBridgeHandler.install();
}
 
Example #24
Source File: PulsarBrokerStarter.java    From pulsar with Apache License 2.0 5 votes vote down vote up
private static ServiceConfiguration loadConfig(String configFile) throws Exception {
    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();
    ServiceConfiguration config = create((new FileInputStream(configFile)), ServiceConfiguration.class);
    // it validates provided configuration is completed
    isComplete(config);
    return config;
}
 
Example #25
Source File: MainApp.java    From purplejs with Apache License 2.0 5 votes vote down vote up
public void start()
    throws Exception
{
    // Setup logging bridge
    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();

    // Add shutdown-hook
    Runtime.getRuntime().addShutdownHook( new Thread()
    {
        @Override
        public void run()
        {
            MainApp.this.stop();
        }
    } );

    // Set some system properties
    System.setProperty( "java.net.preferIPv4Stack", "true" );

    // Print banner
    new BannerPrinter().printBanner();

    // Load settings
    final Settings settings = new ConfigBuilder().build();

    // Configure the server
    final ServerConfigurator serverConfigurator = new ServerConfigurator();
    serverConfigurator.configure( settings );

    // Start the server
    this.server = serverConfigurator.getServer();
    this.server.start();
}
 
Example #26
Source File: SLF4JBridgeActivator.java    From gazpachoquest with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent sce) {
    logger.info("Bridging JUL to SLF4");
    // Jersey uses java.util.logging - bridge to slf4
    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();
}
 
Example #27
Source File: Vividus.java    From vividus with Apache License 2.0 5 votes vote down vote up
private static void createJulToSlf4jBridge()
{
    LogManager.getLogManager().reset();
    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();
    Logger.getLogger("global").setLevel(Level.FINEST);
}
 
Example #28
Source File: LoggingConfig.java    From mirror with Apache License 2.0 5 votes vote down vote up
public synchronized static void init() {
  if (started) {
    return;
  }
  started = true;

  // setup java.util.logging (which grpc-java uses) to go to slf4j
  SLF4JBridgeHandler.removeHandlersForRootLogger();
  SLF4JBridgeHandler.install();

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

  LevelChangePropagator p = new LevelChangePropagator();
  p.setContext(context);
  p.start();
  context.addListener(p);

  PatternLayoutEncoder encoder = new PatternLayoutEncoder();
  encoder.setContext(context);
  encoder.setPattern(pattern);
  encoder.start();

  ConsoleAppender<ILoggingEvent> console = new ConsoleAppender<>();
  console.setContext(context);
  console.setEncoder(encoder);
  console.start();

  Logger root = getLogger(Logger.ROOT_LOGGER_NAME);
  root.detachAndStopAllAppenders();
  root.addAppender(console);
  root.setLevel(Level.INFO);

  getLogger("io.grpc").setLevel(Level.INFO);
  // silence a noisy DNS warning when we cannot resolve the other host
  getLogger("io.grpc.internal.ManagedChannelImpl").setLevel(Level.ERROR);
  // silence "ConnectivityStateManager is already disabled" warning
  getLogger("io.grpc.internal.ChannelExecutor").setLevel(Level.ERROR);
  getLogger("mirror").setLevel(Level.INFO);
}
 
Example #29
Source File: SlackAppServer.java    From java-slack-sdk with MIT License 5 votes vote down vote up
public SlackAppServer(Config config, App apiApp, App oauthApp) {
    this.config = config;
    this.apiApp = apiApp;
    this.oauthApp = oauthApp;

    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();
}
 
Example #30
Source File: JavaUtilLoggingConfigurer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void configure(LogLevel logLevel) {
    if (configured) {
        return;
    }

    LogManager.getLogManager().reset();
    SLF4JBridgeHandler.install();
    Logger.getLogger("").setLevel(java.util.logging.Level.FINE);
    configured = true;
}