下面列出了怎么用org.slf4j.impl.StaticLoggerBinder的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 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);
}
}
/**
* Resets the state of the SLF4J Logback logging provider and system.
*/
public static void resetLogback() {
try {
Method loggerFactoryReset = LoggerFactory.class.getDeclaredMethod("reset");
loggerFactoryReset.setAccessible(true);
loggerFactoryReset.invoke(null);
Method staticLoggerBinderReset = StaticLoggerBinder.class.getDeclaredMethod("reset");
staticLoggerBinderReset.setAccessible(true);
staticLoggerBinderReset.invoke(null);
}
catch (Throwable cause) {
throw new IllegalStateException("Failed to reset Logback", cause);
}
}
private static final void versionSanityCheck() {
try {
String e = StaticLoggerBinder.REQUESTED_API_VERSION;
boolean match = false;
String[] arr$ = API_COMPATIBILITY_LIST;
int len$ = arr$.length;
for(int i$ = 0; i$ < len$; ++i$) {
String aAPI_COMPATIBILITY_LIST = arr$[i$];
if(e.startsWith(aAPI_COMPATIBILITY_LIST)) {
match = true;
}
}
if(!match) {
Util.report("The requested version " + e + " by your slf4j binding is not compatible with " + Arrays.asList(API_COMPATIBILITY_LIST));
Util.report("See http://www.slf4j.org/codes.html#version_mismatch for further details.");
}
} catch (NoSuchFieldError var6) {
} catch (Throwable var7) {
Util.report("Unexpected problem occured during version sanity check", var7);
}
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
final String settings = environment.getProperty("logging.config.src");
if (StringUtils.hasText(settings)) {
try {
final ContextBase context = (ContextBase) StaticLoggerBinder.getSingleton().getLoggerFactory();
final JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
LOG.info("try to update logback configuration to {}", settings);
context.reset();
configurator.doConfigure(new ByteArrayInputStream(settings.getBytes()));
} catch (JoranException e) {
LOG.error("can't load settings", e);
}
}
}
private LoggerContext getLoggerContext() {
ILoggerFactory factory = StaticLoggerBinder.getSingleton().getLoggerFactory();
Assert.isInstanceOf(LoggerContext.class, factory,
String.format("LoggerFactory is not a Logback LoggerContext but Logback is on "
+ "the classpath. Either remove Logback or the competing "
+ "implementation (%s loaded from %s). If you are using "
+ "WebLogic you will need to add 'org.slf4j' to " + "prefer-application-packages in WEB-INF/weblogic.xml",
factory.getClass(), getLocation(factory)));
return (LoggerContext) factory;
}
public static void main(String[] args) throws Exception {
final Logger logger = LoggerFactory.getLogger(App.class);
// Printing the information about the bindings for SLF4J:
Configuration config = getConnectorConfiguration(args);
final StaticLoggerBinder binder = StaticLoggerBinder.getSingleton();
System.out.println("Logger Binding: " + binder.getLoggerFactory());
System.out.println(binder.getLoggerFactoryClassStr());
String dbPassword = config.getString("databasePassword");
config.clearProperty("databasePassword");
logger.info("Configuration for program (with DB password hidden) is: \n{}",
ConfigurationUtils.toString(config));
config.setProperty("databasePassword", dbPassword);
logger.info("GOOGLE_APPLICATION_CREDENTIALS: {}",
System.getenv("GOOGLE_APPLICATION_CREDENTIALS"));
// Properties to be passed directly to Debezium
ImmutableConfiguration debeziumConfig = config.immutableSubset("debezium");
startSender(
config.getString("databaseName"),
config.getString("databaseUsername"),
config.getString("databasePassword"),
config.getString("databaseAddress"),
config.getString("databasePort", "3306"), // MySQL default port is 3306
config.getString("gcpProject"),
config.getString("gcpPubsubTopicPrefix"),
config.getString("offsetStorageFile", DEFAULT_OFFSET_STORAGE_FILE),
config.getString("databaseHistoryFile", DEFAULT_DATABASE_HISTORY_FILE),
config.getBoolean("inMemoryOffsetStorage", false),
config.getBoolean("singleTopicMode", false),
config.getString("whitelistedTables"),
config.getString("databaseManagementSystem", DEFAULT_RDBMS),
debeziumConfig);
}
private static final void bind() {
String msg;
try {
Set e = findPossibleStaticLoggerBinderPathSet();
reportMultipleBindingAmbiguity(e);
StaticLoggerBinder.getSingleton();
INITIALIZATION_STATE = 3;
reportActualBinding(e);
fixSubstitutedLoggers();
} catch (NoClassDefFoundError var2) {
msg = var2.getMessage();
if(!messageContainsOrgSlf4jImplStaticLoggerBinder(msg)) {
failedBinding(var2);
throw var2;
}
INITIALIZATION_STATE = 4;
Util.report("Failed to load class \"org.slf4j.impl.StaticLoggerBinder\".");
Util.report("Defaulting to no-operation (NOP) logger implementation");
Util.report("See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.");
} catch (NoSuchMethodError var3) {
msg = var3.getMessage();
if(msg != null && msg.contains("org.slf4j.impl.StaticLoggerBinder.getSingleton()")) {
INITIALIZATION_STATE = 2;
Util.report("slf4j-api 1.6.x (or later) is incompatible with this binding.");
Util.report("Your binding is version 1.5.5 or earlier.");
Util.report("Upgrade your binding to version 1.6.x.");
}
throw var3;
} catch (Exception var4) {
failedBinding(var4);
throw new IllegalStateException("Unexpected initialization failure", var4);
}
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException
{
super.onStartup(servletContext);
ILoggerFactory loggerFactory = StaticLoggerBinder.getSingleton().getLoggerFactory();
if (loggerFactory instanceof LoggerContext)
{
LoggerContext loggerContext = (LoggerContext) loggerFactory;
loggerContext.setPackagingDataEnabled(false);
log.debug("Disabling logback packaging data");
}
}
@Override
public void execute() throws MojoFailureException {
StaticLoggerBinder.getSingleton().setMavenLog(this.getLog());
if (this.targetDirectory.mkdirs()) {
Logger.info(this, "Directory created: %s", this.targetDirectory);
}
try {
Files.walk(this.sourceDirectory.toPath())
.filter(file -> !file.toFile().isDirectory())
.forEach(this::compile);
} catch (final IOException ex) {
throw new MojoFailureException(
new UncheckedText(
new FormattedText(
"Can't list EO files in %s",
this.sourceDirectory
)
).asString(),
ex
);
}
this.project.addCompileSourceRoot(
this.targetDirectory.getAbsolutePath()
);
Logger.info(
this, "Directory added to sources: %s",
this.targetDirectory
);
}
/**
* Get the home (absolute path) of the task logs on disk
*
* @return the task log home, null if it couldn't be found (usually due to missing appender in logback.xml)
*/
@Nullable
public static String getTaskLogHome() {
LoggerContext loggerContext = (LoggerContext) StaticLoggerBinder.getSingleton().getLoggerFactory();
Appender<ILoggingEvent> appender = loggerContext.getLogger(ROOT_LOGGER_NAME).getAppender("tasklogfile");
if (!(appender instanceof SiftingAppender)) {
// We are forgiving if the task log appender does not exist. It could be that a user had a customized logback.xml
// as of 3.4.1 when task logging was introduced. We don't want to block application start in this scenario.
log.error("Could not find a Logback SiftingAppender named 'tasklogfile' in the logback configuration. " +
"Please check that the 'tasklogfile' appender exists in logback.xml");
return null;
}
SiftingAppender siftingAppender = (SiftingAppender) appender;
// this will create a new appender which ultimately creates a temp.log within the tasks log folder
FileAppender<ILoggingEvent> tempFileAppender = (FileAppender<ILoggingEvent>) siftingAppender.getAppenderTracker()
.getOrCreate("temp", 0L);
// Note that at full execution speed the temp.log may not actually exist yet, but we don't actually need it to
File file = new File(tempFileAppender.getFile());
String taskLogsFolder = file.getParent();
// no need to keep the temp.log file around
tempFileAppender.stop(); // stop the appender to release file lock (windows)
FileUtils.deleteQuietly(file);
return taskLogsFolder;
}
/**
* Returns the current logger-context.
*/
@VisibleForTesting
static LoggerContext loggerContext() {
ILoggerFactory factory = LoggerFactory.getILoggerFactory();
if (factory instanceof LoggerContext) {
return (LoggerContext) factory;
}
// Pax-Logging registers a custom implementation of ILoggerFactory which hides logback; as a workaround
// we set org.ops4j.pax.logging.StaticLogbackContext=true in system.properties and access it statically
return (LoggerContext) StaticLoggerBinder.getSingleton().getLoggerFactory();
}
@Override
public final void execute() throws MojoExecutionException, MojoFailureException {
StaticLoggerBinder staticLoggerBinder = StaticLoggerBinder.getSingleton();
staticLoggerBinder.setLog(getLog());
try {
doExecute();
} finally {
staticLoggerBinder.revokeLog();
}
}
@Override
public void onCreate() {
super.onCreate();
//set loglevel to debug
StaticLoggerBinder.setLogLevel(AndroidLogger.LogLevel.DEBUG);
runtime = AndroidBinderRuntime.init(this);
registerProxy();
}
@Override
public void onCreate() {
super.onCreate();
//set loglevel to debug
StaticLoggerBinder.setLogLevel(AndroidLogger.LogLevel.DEBUG);
//init runtime
runtime = AndroidBinderRuntime.init(this);
registerProvider();
}
@Override
public void onReceive(final Context context, final Intent intent) {
if (Objects.equals(intent.getAction(), ACTION_LOG_LEVEL_CHANGE)) {
if (intent.hasExtra(LOG_LEVEL_TAG)) {
final String logLevelExtra = intent.getStringExtra(LOG_LEVEL_TAG);
final @AndroidLogger.LogLevel int logLevel = StaticLoggerBinder.getValidLogLevel(logLevelExtra);
StaticLoggerBinder.setLogLevel(logLevel);
logger.info(String.format("Set log level to %1$s", logLevelExtra));
}
}
}
@Test
public void testCleanup() throws Exception {
Log4jLoggerFactory factory = (Log4jLoggerFactory) StaticLoggerBinder.getSingleton().getLoggerFactory();
factory.getLogger("test");
Set<LoggerContext> set = factory.getLoggerContexts();
LoggerContext ctx1 = set.toArray(new LoggerContext[0])[0];
assertTrue("LoggerContext is not enabled for shutdown", ctx1 instanceof LifeCycle);
((LifeCycle) ctx1).stop();
set = factory.getLoggerContexts();
assertTrue("Expected no LoggerContexts", set.isEmpty());
}
@Override
public void onCreate() {
SupportSQLiteOpenHelper.Configuration configuration;
super.onCreate();
StaticLoggerBinder.init(this);
log = LoggerFactory.getLogger(DbSyncApplication.class);
log.info("onCreate");
configuration = SupportSQLiteOpenHelper.Configuration.builder(this)
.name("db1")
.callback(new Db1Callback())
.build();
db1OpenHelper = new FrameworkSQLiteOpenHelperFactory()
.create(configuration);
db1OpenHelper.getReadableDatabase();
configuration = SupportSQLiteOpenHelper.Configuration.builder(this)
.name("db2")
.callback(new Db2Callback())
.build();
db2OpenHelper = new FrameworkSQLiteOpenHelperFactory()
.create(configuration);
db2OpenHelper.getReadableDatabase();
configuration = SupportSQLiteOpenHelper.Configuration.builder(this)
.name("db3")
.callback(new Db3Callback())
.build();
db3OpenHelper = new FrameworkSQLiteOpenHelperFactory()
.create(configuration);
db3OpenHelper.getReadableDatabase();
configuration = SupportSQLiteOpenHelper.Configuration.builder(this)
.name("db4")
.callback(new Db4Callback())
.build();
db4OpenHelper = new FrameworkSQLiteOpenHelperFactory()
.create(configuration);
db4OpenHelper.getReadableDatabase();
configuration = SupportSQLiteOpenHelper.Configuration.builder(this)
.name("db5")
.callback(new Db5Callback())
.build();
db5OpenHelper = new FrameworkSQLiteOpenHelperFactory()
.create(configuration);
db5OpenHelper.getReadableDatabase();
}
private static void reportActualBinding(Set<URL> staticLoggerBinderPathSet) {
if(isAmbiguousStaticLoggerBinderPathSet(staticLoggerBinderPathSet)) {
Util.report("Actual binding is of type [" + StaticLoggerBinder.getSingleton().getLoggerFactoryClassStr() + ']');
}
}
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
StaticLoggerBinder.getSingleton().setMavenLog(this.getLog());
}
public void execute () throws MojoExecutionException, MojoFailureException
{
StaticLoggerBinder.getSingleton ().setMavenLog (getLog ());
if (m_aSourceFile == null)
throw new MojoExecutionException ("No Source file specified!");
if (m_aSourceFile.exists () && !m_aSourceFile.isFile ())
throw new MojoExecutionException ("The specified Source file " + m_aSourceFile + " is not a file!");
if (m_aTargetFile == null)
throw new MojoExecutionException ("No Target file specified!");
if (m_aTargetFile.exists ())
{
if (!m_bOverwriteWithoutNotice)
{
// 3.1 Not overwriting the existing file
getLog ().debug ("Skipping Target file '" + m_aTargetFile.getPath () + "' because it already exists!");
}
else
{
if (!m_aTargetFile.isFile ())
throw new MojoExecutionException ("The specified Target file " + m_aTargetFile + " is not a file!");
}
}
try
{
final PSSchema aSchema = new PSReader (new FileSystemResource (m_aSourceFile), null, null).readSchema ();
final IPSQueryBinding aQueryBinding = PSQueryBindingRegistry.getQueryBindingOfNameOrThrow (aSchema.getQueryBinding ());
final PSPreprocessor aPreprocessor = new PSPreprocessor (aQueryBinding);
aPreprocessor.setKeepTitles (m_bKeepTitles);
aPreprocessor.setKeepDiagnostics (m_bKeepDiagnostics);
aPreprocessor.setKeepReports (m_bKeepReports);
aPreprocessor.setKeepEmptyPatterns (m_bKeepEmptyPatterns);
// Pre-process
final PSSchema aPreprocessedSchema = aPreprocessor.getForcedPreprocessedSchema (aSchema);
if (aPreprocessedSchema == null)
throw new SchematronPreprocessException ("Failed to preprocess schema " +
aSchema +
" with query binding " +
aQueryBinding);
// Convert to XML string
final MapBasedNamespaceContext aNSCtx = new MapBasedNamespaceContext ();
aNSCtx.addDefaultNamespaceURI (CSchematron.NAMESPACE_SCHEMATRON);
aNSCtx.addMapping ("xsl", CSchematron.NAMESPACE_URI_XSL);
aNSCtx.addMapping ("svrl", CSVRL.SVRL_NAMESPACE_URI);
// Add all <ns> elements from schema as NS context
for (final PSNS aItem : aSchema.getAllNSs ())
aNSCtx.setMapping (aItem.getPrefix (), aItem.getUri ());
final IXMLWriterSettings XWS = new XMLWriterSettings ().setIndent (EXMLSerializeIndent.INDENT_AND_ALIGN)
.setNamespaceContext (aNSCtx);
final IMicroDocument aDoc = new MicroDocument ();
aDoc.appendChild (aPreprocessedSchema.getAsMicroElement ());
if (MicroWriter.writeToFile (aDoc, m_aTargetFile, XWS).isSuccess ())
getLog ().info ("Successfully wrote preprocessed Schematron file '" + m_aTargetFile.getPath () + "'");
else
getLog ().error ("Error writing preprocessed Schematron file to '" + m_aTargetFile.getPath () + "'");
}
catch (final SchematronException ex)
{
throw new MojoExecutionException ("Error preprocessing Schematron file '" + m_aSourceFile + "'", ex);
}
}
@Override
protected void starting(Description description) {
StaticLoggerBinder.getSingleton().setLog(log);
}
@Override
protected void finished(Description description) {
StaticLoggerBinder.getSingleton().revokeLog();
}
public static JoynrRuntime run(final Context context, final String brokerUri) {
StaticLoggerBinder.setLogLevel(AndroidLogger.LogLevel.DEBUG);
logger.debug("Starting...");
return initClusterController(context, brokerUri, new Properties());
}
/**
* Private ctor to avoid direct instantiation of the class.
*/
private StaticLoggerBinder ()
{}
/**
* Return the singleton of this class.
*
* @return The StaticLoggerBinder singleton
*/
public static StaticLoggerBinder getSingleton ()
{
return StaticLoggerBinder.SINGLETON;
}