下面列出了怎么用org.slf4j.bridge.SLF4JBridgeHandler的API类实例代码及写法,或者点击链接到github查看源代码。
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;
}
};
}
/**
* 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);
}
}
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);
}
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);
}
}
}
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();
}
@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();
}
@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);
}
@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();
}
}
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);
}
public Component() {
this.locator = ServiceLocatorUtilities.createAndPopulateServiceLocator();
ServiceLocatorUtilities.addOneConstant(this.locator, this);
// Optionally remove existing handlers attached to j.u.l root logger
SLF4JBridgeHandler.removeHandlersForRootLogger();
// add SLF4JBridgeHandler to java.util.logging's root logger
SLF4JBridgeHandler.install();
}
private static void createJulToSlf4jBridge()
{
LogManager.getLogManager().reset();
SLF4JBridgeHandler.removeHandlersForRootLogger();
SLF4JBridgeHandler.install();
Logger.getLogger("global").setLevel(Level.FINEST);
}
private static KafkaServiceConfiguration loadConfig(String configFile) throws Exception {
SLF4JBridgeHandler.removeHandlersForRootLogger();
SLF4JBridgeHandler.install();
KafkaServiceConfiguration config = ConfigurationUtils.create(
new FileInputStream(configFile),
KafkaServiceConfiguration.class);
// it validates provided configuration is completed
isComplete(config);
return config;
}
public void configure(LogLevel logLevel) {
if (configured) {
return;
}
LogManager.getLogManager().reset();
SLF4JBridgeHandler.install();
Logger.getLogger("").setLevel(java.util.logging.Level.FINE);
configured = true;
}
public void configure(LogLevel logLevel) {
if (configured) {
return;
}
LogManager.getLogManager().reset();
SLF4JBridgeHandler.install();
Logger.getLogger("").setLevel(java.util.logging.Level.FINE);
configured = true;
}
/**
* Method starts the database package and it's libraries by loading all their bean factories each of which is
* responsible to load it's own code henceforth.
*
* List of bean factories is maintained under {@code /src/main/resources/launcher-config.xml}.
*
* TODO: 1) I had a dream.. a dream that some day main functions will parse CLI arguments.
*
* @param args who cares.. for now..
*/
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
logger.info("Starting BlobCity DB\"");
// Pre-startup tasks below
logger.debug("Configuring JUL Loggers");
SLF4JBridgeHandler.removeHandlersForRootLogger();
SLF4JBridgeHandler.install();
System.setProperty("jna.debug_load", "true");
System.setProperty("jna.debug_load.jna", "true");
// System.setProperty("java.library.path", "/lib");
System.setProperty("jna.library.path", "/lib64");
// Startup tasks below
logger.debug("Performing database launch tasks");
try {
loadBeanConfigs(); // This task launches the database
// Any other future tasks can go here as method class
initEngine();
} catch (ClassNotFoundException ex) {
logger.error("Launching BlobCity DB has failed!", ex);
}
logger.info("BlobCity DB successfully started in " + (System.currentTimeMillis() - startTime) / 1000 + " seconds");
logger.info("Setting log level to ERROR. Change by using set-log-level {log_level} CLI command");
LogManager.getRootLogger().setLevel(org.apache.log4j.Level.ERROR);
// it is assumed that startup failures are managed and appropriate logs are generated
}
protected Application configure() {
SLF4JBridgeHandler.removeHandlersForRootLogger();
SLF4JBridgeHandler.install();
enable(TestProperties.LOG_TRAFFIC);
return new ExampleSecretInjectionApplication<User>();
}
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();
}
@Override
public void start( BundleContext context ) throws Exception
{
// Remove existing handlers attached to j.u.l root logger
SLF4JBridgeHandler.removeHandlersForRootLogger();
SLF4JBridgeHandler.install();
}
/**
* Shut down LOGBack.
* This isn't strictly necessary, but recommended for shutting down
* logback in a scenario where the host VM stays alive (for example, when
* shutting down an application in a J2EE environment).
*
* @param uninstallJULBridge should an attempt be made to uninstall the JUL bridge
*/
public static void shutdownLogging(boolean uninstallJULBridge) {
ContextSelector selector = ContextSelectorStaticBinder.getSingleton().getContextSelector();
LoggerContext loggerContext = selector.getLoggerContext();
String loggerContextName = loggerContext.getName();
LoggerContext context = selector.detachLoggerContext(loggerContextName);
if (uninstallJULBridge) {
SLF4JBridgeHandler.uninstall();
}
context.stop();
}
/**
* Entry point. You must provide a single argument on the command line: a valid Graph API access token.
*
* @param args
* Command-line arguments.
* @throws IllegalArgumentException
* If no command-line arguments are provided.
*/
public static void main(String[] args) {
if (args.length == 0)
throw new IllegalArgumentException(
"You must provide an OAuth access token parameter. See README for more information.");
SLF4JBridgeHandler.removeHandlersForRootLogger();
SLF4JBridgeHandler.install();
new GraphReaderExample(args[0]).runEverything();
}
public SlackAppServer(Config config, App apiApp, App oauthApp) {
this.config = config;
this.apiApp = apiApp;
this.oauthApp = oauthApp;
SLF4JBridgeHandler.removeHandlersForRootLogger();
SLF4JBridgeHandler.install();
}
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);
}
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();
}
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;
}
@Override
protected void initializeLogging() {
super.initializeLogging();
// Move all java util logging logs to SLF4j
SLF4JBridgeHandler.removeHandlersForRootLogger();
SLF4JBridgeHandler.install();
}
/**
* 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);
}
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();
}
public void configure(LogLevel logLevel) {
if (configured) {
return;
}
LogManager.getLogManager().reset();
SLF4JBridgeHandler.install();
Logger.getLogger("").setLevel(java.util.logging.Level.FINE);
configured = true;
}
public void configure(LogLevel logLevel) {
if (configured) {
return;
}
LogManager.getLogManager().reset();
SLF4JBridgeHandler.install();
Logger.getLogger("").setLevel(java.util.logging.Level.FINE);
configured = true;
}
@After
public void tearDown() throws Exception {
// restore
Logger.getRootLogger().removeAllAppenders();
for (Appender appender : appenders) {
Logger.getRootLogger().addAppender(appender);
}
SLF4JBridgeHandler.uninstall();
}