下面列出了怎么用org.slf4j.ILoggerFactory的API类实例代码及写法,或者点击链接到github查看源代码。
/***
* 根据 spaceId 在日志空间里移除指定 spaceName 的 ILoggerFactory
*
* @param spaceId 指定的日志空间名称
* @return 被移除的 ILoggerFactory;不存在指定的 spaceName,则返回 null
*/
public static ILoggerFactory removeILoggerFactoryBySpaceId(SpaceId spaceId) {
if (spaceId == null) {
return null;
}
SpaceInfo spaceInfo = SPACES_MAP.get(spaceId);
if (isSpaceILoggerFactoryExisted(spaceId)) {
AbstractLoggerSpaceFactory iLoggeriFactory = spaceInfo.getAbstractLoggerSpaceFactory();
spaceInfo.setAbstractLoggerSpaceFactory(null);
Logger rootLogger = iLoggeriFactory.getLogger(Logger.ROOT_LOGGER_NAME);
rootLogger.warn("Log Space Name[" + spaceId.toString()
+ "] is Removed from Current Log Space Manager!");
return iLoggeriFactory;
}
return null;
}
@Override
public void setWorkDir(File path) {
if (path == null) {
throw new IllegalArgumentException("Work directory is null");
}
if (!path.exists()) {
path.mkdirs();
}
this.workDir = path;
System.setProperty("log.home", path.getAbsolutePath());
ILoggerFactory fac = LoggerFactory.getILoggerFactory();
if (fac != null && fac instanceof LoggerContext) {
LoggerContext lc = (LoggerContext) fac;
lc.getStatusManager().clear();
lc.reset();
lc.putProperty("log.home", path.getAbsolutePath());
ContextInitializer ci = new ContextInitializer(lc);
try {
ci.autoConfig();
} catch (JoranException e) {
e.printStackTrace();
}
}
}
private void configureLogging() {
System.setProperty(SPRING_BOOT_DATA_GEMFIRE_LOG_LEVEL_PROPERTY, getTestLogLevel().toString());
ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();
assertThat(loggerFactory).isInstanceOf(LoggerContext.class);
LoggerContext loggerContext = (LoggerContext) loggerFactory;
try {
new ContextInitializer(loggerContext).autoConfig();
}
catch (Exception cause) {
throw newIllegalStateException("Failed to configure and initialize SLF4J/Logback logging context", cause);
}
}
private void configureLogger() throws MalformedURLException, JoranException {
// Check if SLF4J is bound to logback in the current environment
ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();
if (!(loggerFactory instanceof LoggerContext)) {
return;
}
LoggerContext context = (LoggerContext) loggerFactory;
ContextInitializer contextInitializer = new ContextInitializer(context);
URL url = contextInitializer.findURLOfDefaultConfigurationFile(false);
if (url == null) {
// The logger context was not initialized using configuration file, initialize it with the logback template.
File twillLogback = new File(Constants.Files.RUNTIME_CONFIG_JAR, Constants.Files.LOGBACK_TEMPLATE);
if (twillLogback.exists()) {
contextInitializer.configureByResource(twillLogback.toURI().toURL());
}
}
KafkaAppender kafkaAppender = getKafkaAppender(context);
kafkaAppender.start();
// Attach the KafkaAppender to the root logger
context.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME).addAppender(kafkaAppender);
}
/**
* Set the log level for the requested logger name.
*
* @param loggerName name of the logger
* @param logLevel the log level to set to.
* @return the current log level of the given logger. If there is no log level configured for the given logger or
* if the logging implementation is not logback, {@code null} will be returned
*/
@Nullable
private String setLogLevel(String loggerName, @Nullable String logLevel) {
ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();
if (!(loggerFactory instanceof LoggerContext)) {
LOG.error("LoggerFactory is not a logback LoggerContext, cannot make the log level change");
return null;
}
LoggerContext loggerContext = (LoggerContext) loggerFactory;
ch.qos.logback.classic.Logger logger = loggerContext.getLogger(loggerName);
LogEntry.Level oldLogLevel = logger.getLevel() == null ? null :
LogEntry.Level.valueOf(logger.getLevel().toString());
LOG.debug("Log level of {} changed from {} to {}", loggerName, oldLogLevel, logLevel);
logger.setLevel(logLevel == null ? null : Level.toLevel(logLevel, Level.ERROR));
return oldLogLevel == null ? null : oldLogLevel.name();
}
@Before
public void init() throws Exception {
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
request = mock(HttpServletRequest.class);
response = mock(HttpServletResponse.class);
registry = new EventLoggingRegistry();
EventLogDefinition eld = new EventLogDefinition();
eld.setRegistry(registry);
eld.setLogName("ACCESS-LOG");
eld.register();
loggerFactory = mock(ILoggerFactory.class);
oldLoggerFactory = HttpRequestLogger.setLoggerFactory(loggerFactory);
eventLog = mock(Logger.class);
}
private void flushLogs() {
final long millisToWait = 100;
LOG.info(
"Attempting to flush logs and wait {} ...",
JavaUtils.durationFromMillis(millisToWait)
);
ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();
if (loggerFactory instanceof LoggerContext) {
LoggerContext context = (LoggerContext) loggerFactory;
context.stop();
}
try {
Thread.sleep(millisToWait);
} catch (Exception e) {
LOG.info("While sleeping for log flush", e);
}
}
@GetMapping
public String init(Model model) {
ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory();
if (!(iLoggerFactory instanceof LoggerContext)) {
throw new RuntimeException("Logger factory is not a Logback logger context");
}
LoggerContext loggerContext = (LoggerContext) iLoggerFactory;
List<Logger> loggers = new ArrayList<>();
for (ch.qos.logback.classic.Logger logger : loggerContext.getLoggerList()) {
if (logger.getLevel() != null || logger.iteratorForAppenders().hasNext()) {
loggers.add(logger);
}
}
model.addAttribute("loggers", loggers);
model.addAttribute("levels", LOG_LEVELS);
model.addAttribute("hasWritePermission", SecurityUtils.currentUserIsSu());
return "view-logmanager";
}
@PreAuthorize("hasAnyRole('ROLE_SU')")
@PostMapping("/loggers/reset")
@ResponseStatus(HttpStatus.OK)
public void resetLoggers() {
ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory();
if (!(iLoggerFactory instanceof LoggerContext)) {
throw new RuntimeException("Logger factory is not a Logback logger context");
}
LoggerContext loggerContext = (LoggerContext) iLoggerFactory;
ContextInitializer ci = new ContextInitializer(loggerContext);
URL url = ci.findURLOfDefaultConfigurationFile(true);
loggerContext.reset();
try {
ci.configureByResource(url);
} catch (JoranException e) {
throw new RuntimeException("Error reloading log configuration", e);
}
}
public static ServiceLocator initServiceLocator() {
DefaultServiceLocator locator = MavenRepositorySystemUtils.newServiceLocator();
locator.setErrorHandler(
new DefaultServiceLocator.ErrorHandler() {
@Override
public void serviceCreationFailed(Class<?> type, Class<?> impl, Throwable exception) {
throw new RuntimeException(
String.format(
"Failed to initialize service %s, implemented by %s: %s",
type.getName(), impl.getName(), exception.getMessage()),
exception);
}
});
locator.addService(RepositoryConnectorFactory.class, BasicRepositoryConnectorFactory.class);
locator.addService(TransporterFactory.class, HttpTransporterFactory.class);
locator.addService(TransporterFactory.class, FileTransporterFactory.class);
// Use a no-op logger. Leaving this out would introduce a runtime dependency on log4j
locator.addService(ILoggerFactory.class, NOPLoggerFactory.class);
// Also requires log4j
// locator.addService(ILoggerFactory.class, Log4jLoggerFactory.class);
return locator;
}
/**
* Set log level
*
* @param level DEBUG
*/
public static void setLogLevel(String level) {
ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();
if (loggerFactory instanceof LoggerContext) {
LoggerContext loggerContext = (LoggerContext)loggerFactory;
Logger logger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME);
((ch.qos.logback.classic.Logger)logger).setLevel(Level.toLevel(level));
return;
}
throw new IllegalStateException("not support the log context object");
}
@Before
public void initLogback() throws JoranException {
InternalLoggerFactory.setCurrentLoggerType(InternalLoggerFactory.LOGGER_SLF4J);
System.setProperty("loggingDir", loggingDir);
ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory();
JoranConfigurator joranConfigurator = new JoranConfigurator();
joranConfigurator.setContext((Context) iLoggerFactory);
URL logbackConfigFile = Slf4jLoggerFactoryTest.class.getClassLoader().getResource("logback_test.xml");
if (logbackConfigFile == null) {
throw new RuntimeException("can't find logback_test.xml");
} else {
joranConfigurator.doConfigure(logbackConfigFile);
}
}
@Before
public void initLogback() throws JoranException {
InternalLoggerFactory.setCurrentLoggerType(InternalLoggerFactory.LOGGER_SLF4J);
System.setProperty("loggingDir", loggingDir);
ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory();
JoranConfigurator joranConfigurator = new JoranConfigurator();
joranConfigurator.setContext((Context) iLoggerFactory);
URL logbackConfigFile = Slf4jLoggerFactoryTest.class.getClassLoader().getResource("logback_test.xml");
if (logbackConfigFile == null) {
throw new RuntimeException("can't find logback_test.xml");
} else {
joranConfigurator.doConfigure(logbackConfigFile);
}
}
/**
* issue#234
*/
@Test
public void testLogClassCastBug() {
Throwable throwable = null;
try {
ILoggerFactory iLoggerFactory = (ILoggerFactory) this.getClass().getClassLoader()
.loadClass("org.apache.logging.slf4j.Log4jLoggerFactory").newInstance();
} catch (Throwable t) {
throwable = t;
}
Assert.assertNull(throwable);
}
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;
}
private Object getLocation(ILoggerFactory factory) {
try {
ProtectionDomain protectionDomain = factory.getClass().getProtectionDomain();
CodeSource codeSource = protectionDomain.getCodeSource();
if (codeSource != null) {
return codeSource.getLocation();
}
} catch (SecurityException ex) {
// Unable to determine location
}
return "unknown location";
}
/**
* Instantiates a new Cas logger factory.
* Configures the reflection scanning engine to be prepared to scan <code>org.slf4j.impl</code>
* in order to find other available factories.
*/
public CasLoggerFactory() {
this.loggerMap = new ConcurrentHashMap<>();
final Collection<URL> set = ClasspathHelper.forPackage(PACKAGE_TO_SCAN);
final Reflections reflections = new Reflections(new ConfigurationBuilder().addUrls(set).setScanners(new SubTypesScanner()));
final Set<Class<? extends ILoggerFactory>> subTypesOf = reflections.getSubTypesOf(ILoggerFactory.class);
subTypesOf.remove(this.getClass());
if (subTypesOf.size() > 1) {
Util.report("Multiple ILoggerFactory bindings are found on the classpath:");
for (final Class<? extends ILoggerFactory> c : subTypesOf) {
Util.report("* " + c.getCanonicalName());
}
}
if (subTypesOf.isEmpty()) {
final RuntimeException e = new RuntimeException("No ILoggerFactory could be found on the classpath."
+ " CAS cannot determine the logging framework."
+ " Examine the project dependencies and ensure that there is one and only one logging framework available.");
Util.report(e.getMessage(), e);
throw e;
}
this.realLoggerFactoryClass = subTypesOf.iterator().next();
Util.report("ILoggerFactory to be used for logging is: " + this.realLoggerFactoryClass.getName());
}
/**
* Resolves the SLF4J, Logback {@link LoggerContext}.
*
* If the {@link LoggerContext} could not be resolve then the returned {@link Optional}
* will be {@link Optional#empty() empty}.
*
* @return an {@link Optional} {@link LoggerContext}.
* @see ch.qos.logback.classic.LoggerContext
*/
public static Optional<LoggerContext> resolveLoggerContext() {
ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();
LoggerContext resolvedLoggerContext = loggerFactory instanceof LoggerContext
? (LoggerContext) loggerFactory
: null;
return Optional.ofNullable(resolvedLoggerContext);
}
public static void forceFlush() {
ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();
if (loggerFactory instanceof LoggerContext) {
Appender<ILoggingEvent> appender = ((LoggerContext) loggerFactory).getLogger(Logger.ROOT_LOGGER_NAME)
.getAppender("KAFKA");
if (appender != null && appender instanceof KafkaAppender) {
((KafkaAppender) appender).forceFlush();
}
}
}
@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");
}
}
@Before
public void initLogback() throws JoranException {
InternalLoggerFactory.setCurrentLoggerType(InternalLoggerFactory.LOGGER_SLF4J);
System.setProperty("loggingDir", loggingDir);
ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory();
JoranConfigurator joranConfigurator = new JoranConfigurator();
joranConfigurator.setContext((Context) iLoggerFactory);
URL logbackConfigFile = Slf4jLoggerFactoryTest.class.getClassLoader().getResource("logback_test.xml");
if (logbackConfigFile == null) {
throw new RuntimeException("can't find logback_test.xml");
} else {
joranConfigurator.doConfigure(logbackConfigFile);
}
}
public static void immediateFlushBufferedLogs() {
ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();
if (loggerFactory.getClass().getName().equals(LogbackLoggerContextClassName)) {
// Use reflection to force the flush on the logger
try {
Class<?> logbackLoggerContextClass = Class.forName(LogbackLoggerContextClassName);
Method stop = logbackLoggerContextClass.getMethod("stop");
stop.invoke(loggerFactory);
} catch (Throwable t) {
LOG.info("Failed to flush logs", t);
}
}
}
/**
* 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();
}
private ConcurrentMap<String, Logger> clearIlogger() throws Exception {
ILoggerFactory ilogger = LoggerFactory.getILoggerFactory();
Field field = SimpleLoggerFactory.class.getDeclaredField("loggerMap");
field.setAccessible(true);
ConcurrentMap<String, Logger> map = (ConcurrentMap<String, Logger>) field
.get(ilogger);
map.clear();
return map;
}
public static void applyConfiguration(final DolphinLoggerConfiguration configuration) {
final ILoggerFactory factory = LoggerFactory.getILoggerFactory();
Objects.requireNonNull(factory);
if(factory instanceof DolphinLoggerFactory) {
((DolphinLoggerFactory) factory).configure(configuration);
} else {
throw new IllegalStateException(LoggerFactory.class + " is not of type " + DolphinLoggerFactory.class);
}
}
public DefaultJsonixContext(ILoggerFactory loggerFactory) {
this.loggerFactory = new LevelledLoggerFactoryWrapper(loggerFactory) {
@Override
protected int getLevel() {
return DefaultJsonixContext.this.getLogLevel();
}
};
}
@Override
public void onActivated(Options opts) throws BadCommandLineException {
final ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory();
if (iLoggerFactory instanceof NOPLoggerFactory) {
System.err
.println("You seem to be using the NOP provider of the SLF4j logging facade. "
+ "With this configuration, log messages will be completely suppressed. "
+ "Please consider adding a SLF4j provider (for instance slf4j-simple) to enable logging.");
}
}
public List<LoggerConfig> getLoggers() {
List<LoggerConfig> loggers = new ArrayList<LoggerConfig>();
ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();
if (loggerFactory instanceof LoggerContext) {
LoggerContext context = (LoggerContext) loggerFactory;
for (ch.qos.logback.classic.Logger l : context.getLoggerList()) {
loggers.add(new LoggerConfig(l.getName(), l.getEffectiveLevel().toString()));
}
}
return loggers;
}
public void update(LoggerConfig logger2Change) {
ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();
if (loggerFactory instanceof LoggerContext) {
LoggerContext context = (LoggerContext) loggerFactory;
context.getLogger(logger2Change.getName()).setLevel(Level.valueOf(logger2Change.getLevel()));
}
}
public static void setupLogger() {
ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();
if (loggerFactory instanceof LoggerContext) {
LoggerContext lc = (LoggerContext) loggerFactory;
if (U.isEmpty(lc.getCopyOfPropertyMap())) {
Logger root = lc.getLogger(Logger.ROOT_LOGGER_NAME);
root.setLevel(Level.INFO);
}
}
}