下面列出了怎么用java.util.logging.LogManager的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void run() {
try {
if (getServer() != null) {
Catalina.this.stop();
}
} catch (Throwable ex) {
ExceptionUtils.handleThrowable(ex);
log.error(sm.getString("catalina.shutdownHookFail"), ex);
} finally {
// If JULI is used, shut JULI down *after* the server shuts down
// so log messages aren't lost
LogManager logManager = LogManager.getLogManager();
if (logManager instanceof ClassLoaderLogManager) {
((ClassLoaderLogManager) logManager).shutdown();
}
}
}
public void testLog() throws Exception {
assertFalse(err.isLoggable(ErrorManager.INFORMATIONAL));
err.log("some msg");
String s = readLog();
assertTrue(s.indexOf("some msg") == -1);
assertTrue(err.isLoggable(ErrorManager.WARNING));
err.log(ErrorManager.WARNING, "another msg");
s = readLog();
assertTrue(s.indexOf("another msg") != -1);
ErrorManager err2 = err.getInstance("foo.bar.baz");
assertFalse(err2.isLoggable(ErrorManager.INFORMATIONAL));
err2.log("sub msg #1");
s = readLog();
assertTrue(s.indexOf("sub msg #1") == -1);
System.setProperty("quux.hoho.level", "0");
LogManager.getLogManager().readConfiguration();
err2 = err.getInstance("quux.hoho.yaya");
assertTrue(err2.isLoggable(ErrorManager.INFORMATIONAL));
err2.log("sub msg #2");
s = readLog();
assertTrue(s, s.indexOf("sub msg #2") != -1);
assertTrue(s, s.indexOf("quux.hoho.yaya") != -1);
}
public static void main(String[] args) throws InterruptedException{
Thread t1 = new Thread(new Runnable() {
public void run() {
randomDelay();
// Trigger Logger.<clinit>
Logger.getAnonymousLogger();
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
randomDelay();
// Trigger LogManager.<clinit>
LogManager.getLogManager();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("\nTest passed");
}
/**
* Visible version of {@link java.util.logging.LogManager#getFilterProperty(String, java.util.logging.Filter)}.
*
* We return an instance of the class named by the "name" property.
*
* If the property is not defined or has problems we return the defaultValue.
*/
@Nullable
public static Filter getFilterProperty(@Nonnull LogManager manager, @Nullable String name, @Nullable Filter defaultValue) {
if (name == null) {
return defaultValue;
}
String val = manager.getProperty(name);
try {
if (val != null) {
Class clz = ClassLoader.getSystemClassLoader().loadClass(val);
return (Filter) clz.newInstance();
}
} catch (Exception ex) {
// We got one of a variety of exceptions in creating the
// class or creating an instance.
// Drop through.
}
// We got an exception. Return the defaultValue.
return defaultValue;
}
public static void testLoadingMain() {
Bridge.desactivate();
Logger bar = new Bridge.CustomLogger("com.foo.Bar");
LogManager.getLogManager().addLogger(bar);
assertNotNull(bar.getParent());
testParent(bar);
testParent(LogManager.getLogManager().getLogger("global"));
testParent(LogManager.getLogManager().getLogger(bar.getName()));
Bridge.changeContext();
Logger foo = new Bridge.CustomLogger("com.foo.Foo");
boolean b = LogManager.getLogManager().addLogger(foo);
assertEquals(Boolean.TRUE, Boolean.valueOf(b));
assertNotNull(foo.getParent());
testParent(foo);
testParent(LogManager.getLogManager().getLogger("global"));
testParent(LogManager.getLogManager().getLogger(foo.getName()));
}
public void configureHandler( Level baseLevel )
{
Handler[] hList = LogManager.getLogManager().getLogger( "" ).getHandlers();
for ( Handler h : hList )
{
if ( h instanceof ThreadedFileHandler )
return;
}
setLevel( baseLevel );
setFormatter( new SimpleFormatter() );
LogManager.getLogManager().getLogger( "" ).addHandler( this );
}
/**
* Tests that the given listeners are invoked the expected number of
* times.
*/
static void test(Listener[] listeners, int... expected) throws Exception {
// reset counts
for (Listener listener : listeners) {
listener.reset();
}
// re-reading configuration causes events to be fired
LogManager.getLogManager().readConfiguration();
// check event listeners invoked as expected
for (int i = 0; i < expected.length; i++) {
assertTrue(listeners[i].fireCount() == expected[i],
"Unexpected event count");
}
}
public static void testLoadingMain() {
Bridge.desactivate();
Logger bar = new Bridge.CustomLogger("com.foo.Bar");
LogManager.getLogManager().addLogger(bar);
assertNotNull(bar.getParent());
testParent(bar);
testParent(LogManager.getLogManager().getLogger("global"));
testParent(LogManager.getLogManager().getLogger(bar.getName()));
Bridge.changeContext();
Logger foo = new Bridge.CustomLogger("com.foo.Foo");
boolean b = LogManager.getLogManager().addLogger(foo);
assertEquals(Boolean.TRUE, Boolean.valueOf(b));
assertNotNull(foo.getParent());
testParent(foo);
testParent(LogManager.getLogManager().getLogger("global"));
testParent(LogManager.getLogManager().getLogger(foo.getName()));
}
public void testCanInfluenceBehaviourBySettingALevelPropertyOnExistingParent() throws Exception {
System.setProperty("ha.nu.level", "100");
Logger l = Logger.getLogger("ha.nu.wirta");
LogManager.getLogManager().readConfiguration();
l.log(Level.FINER, "Finer level msg");
Pattern p = Pattern.compile("FINER.*Finer level msg");
String disk = readLog(true);
Matcher d = p.matcher(disk);
if (!d.find()) {
fail("msg shall be logged to file: " + disk);
}
}
/**
* Activates default configuration when a configuration file is missing.
*
* @throws IOException
*/
private void startUpFallback() throws IOException {
String pattern = Factory.getDataPath() + "/IBM_TECHNICAL_SUPPORT/org.openntf.%u.%g.log";
Logger oodLogger = Logger.getLogger("org.openntf.domino");
oodLogger.setLevel(Level.WARNING);
DefaultFileHandler dfh = new DefaultFileHandler(pattern, 50000, 100, true);
dfh.setFormatter(new FileFormatter());
dfh.setLevel(Level.WARNING);
oodLogger.addHandler(dfh);
DefaultConsoleHandler dch = new DefaultConsoleHandler();
dch.setFormatter(new ConsoleFormatter());
dch.setLevel(Level.WARNING);
oodLogger.addHandler(dch);
OpenLogHandler olh = new OpenLogHandler();
olh.setLogDbPath("OpenLog.nsf");
olh.setLevel(Level.WARNING);
oodLogger.addHandler(olh);
LogManager.getLogManager().addLogger(oodLogger);
}
public static void testThree() {
for (int i=0; i<3 ; i++) {
Logger logger1 = LogManager.getLogManager().getLogger("");
Logger logger1b = LogManager.getLogManager().getLogger("");
assertNotNull(logger1);
assertNotNull(logger1b);
assertEquals(logger1, logger1b);
Bridge.changeContext();
Logger logger2 = LogManager.getLogManager().getLogger("");
Logger logger2b = LogManager.getLogManager().getLogger("");
assertNotNull(logger2);
assertNotNull(logger2b);
assertEquals(logger2, logger2b);
assertEquals(logger1, logger2);
}
}
@Override
public void run() {
while (goOn) {
try {
if (Math.random() > CONFSYNCTHRESHOLD) {
// calling readConfiguration while holding a lock can
// increase deadlock probability...
synchronized(fakeConfExternalLock()) {
LogManager.getLogManager().readConfiguration();
}
} else {
LogManager.getLogManager().readConfiguration();
}
Logger blah = Logger.getLogger(BLAH);
blah.setLevel(Level.FINEST);
blah.fine(BLAH);
readCount.incrementAndGet();
pause(1);
} catch (Exception x) {
fail(x);
}
}
}
/**
* Tests that the given listeners are invoked the expected number of
* times.
*/
static void test(Listener[] listeners, int... expected) throws Exception {
// reset counts
for (Listener listener : listeners) {
listener.reset();
}
// re-reading configuration causes events to be fired
LogManager.getLogManager().readConfiguration();
// check event listeners invoked as expected
for (int i = 0; i < expected.length; i++) {
assertTrue(listeners[i].fireCount() == expected[i],
"Unexpected event count");
}
}
public static @Nullable ClassLogger find(@Nullable Logger parent, Class<?> klass, @Nullable String instanceKey) {
if(parent == null) {
parent = Logger.getLogger("");
}
String name = getName(klass, instanceKey);
if(parent instanceof ClassLogger && Objects.equals(parent.getName(), name)) {
// If the given parent logger looks exactly like the logger
// we are supposed to return, just use it. This makes it easy
// to replace a parent logger with a child once only e.g.
//
// logger = ClassLogger.get(logger, getClass(), "myInstance")
return (ClassLogger) parent;
}
LogManager lm = LogManager.getLogManager();
Logger logger = lm.getLogger(name);
if(logger instanceof ClassLogger) {
if(parent != logger.getParent()) {
throw new IllegalStateException("Already registred logger " + name + " has a different parent than the one requested:\n old = " + logger.getParent() + "\n new = " + parent);
}
return (ClassLogger) logger;
} else {
return null;
}
}
public static void testFive() {
for (int i=0; i<3 ; i++) {
Logger logger1 = LogManager.getLogManager().getLogger(Logger.GLOBAL_LOGGER_NAME);
Logger logger1b = LogManager.getLogManager().getLogger(Logger.GLOBAL_LOGGER_NAME);
assertNotNull(logger1);
assertNotNull(logger1b);
assertEquals(logger1, logger1b);
Bridge.changeContext();
Logger logger2 = LogManager.getLogManager().getLogger(Logger.GLOBAL_LOGGER_NAME);
Logger logger2b = LogManager.getLogManager().getLogger(Logger.GLOBAL_LOGGER_NAME);
assertNotNull(logger2);
assertNotNull(logger2b);
assertEquals(logger2, logger2b);
assertEquals(logger1, logger2);
}
}
public static void main(String[] args) throws InterruptedException{
Thread t1 = new Thread(new Runnable() {
public void run() {
randomDelay();
// Trigger Logger.<clinit>
Logger.getAnonymousLogger();
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
randomDelay();
// Trigger LogManager.<clinit>
LogManager.getLogManager();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("\nTest passed");
}
public static void readJavaUtilLoggingConfigFromClasspath() {
InputStream inputStream = ReflectUtil.getResourceAsStream("logging.properties");
try {
if (inputStream != null) {
LogManager.getLogManager().readConfiguration(inputStream);
String redirectCommons = LogManager.getLogManager().getProperty("redirect.commons.logging");
if ((redirectCommons != null) && (!redirectCommons.equalsIgnoreCase("false"))) {
System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Jdk14Logger");
}
}
} catch (Exception e) {
throw new PvmException("couldn't initialize logging properly", e);
} finally {
IoUtil.closeSilently(inputStream);
}
}
protected void configureLog(FileSystem fs, String[] args) throws IOException {
String baseDir = getBaseExecDir();
Files.createDirectories(fs.getPath(baseDir));
if (System.getProperty("java.util.logging.config.file") == null) {
logger.atInfo().log("Setting up LogManager");
String level = isEnableLogging(args) ? "INFO" : "OFF";
LogManager.getLogManager().readConfiguration(new ByteArrayInputStream((
"handlers=java.util.logging.FileHandler\n"
+ ".level=INFO\n"
+ "java.util.logging.FileHandler.level=" + level +"\n"
+ "java.util.logging.FileHandler.pattern="
+ baseDir + "/copybara-%g.log\n"
+ "java.util.logging.FileHandler.count=10\n"
+ "java.util.logging.FileHandler.formatter=java.util.logging.SimpleFormatter\n"
+ "java.util.logging.SimpleFormatter.format="
+ "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$-6s %2$s %5$s%6$s%n")
.getBytes(StandardCharsets.UTF_8)
));
}
}
/** Runs the type in a new classloader that recreates brave classes */
public static void assertRunIsUnloadable(Class<? extends Runnable> runnable, ClassLoader parent) {
// We can't use log4j2's log manager. More importantly, we want to make sure loggers don't hold
// our test classloader from being collected.
System.setProperty("java.util.logging.manager", LogManager.class.getName());
assertThat(LogManager.getLogManager().getClass()).isSameAs(LogManager.class);
WeakReference<ClassLoader> loader;
try {
loader = invokeRunFromNewClassLoader(runnable, parent);
} catch (Exception e) {
throw new AssertionError(e);
}
GarbageCollectors.blockOnGC();
assertThat(loader.get())
.withFailMessage(runnable + " includes state that couldn't be garbage collected")
.isNull();
}
Logger getBackendLogger(String name) {
if (isSystem) {
return LoggingProviderImpl.getLogManagerAccess().demandLoggerFor(
LogManager.getLogManager(), name, Thread.class.getModule());
} else {
return Logger.getLogger(name);
}
}
private String getProperty(String name, String defaultValue) {
String value = LogManager.getLogManager().getProperty(name);
if (value == null) {
value = defaultValue;
} else {
value = value.trim();
}
return value;
}
private String getProperty(String name, String defaultValue) {
String value = LogManager.getLogManager().getProperty(name);
if (value == null) {
value = defaultValue;
} else {
value = value.trim();
}
return value;
}
public static void main(String[] args) throws IOException {
System.setProperty(CONFIG_FILE_KEY,
new File(System.getProperty("test.src", "."),
"rootlogger.properties").getAbsolutePath());
System.out.println(CONFIG_FILE_KEY + "="
+ System.getProperty(CONFIG_FILE_KEY));
if (! new File(System.getProperty(CONFIG_FILE_KEY)).canRead()) {
throw new RuntimeException("can't read config file: "
+ System.getProperty(CONFIG_FILE_KEY));
}
final String configFile = System.getProperty(CONFIG_FILE_KEY);
test("no security");
LogManager.getLogManager().readConfiguration();
Policy.setPolicy(new SimplePolicy(configFile));
System.setSecurityManager(new SecurityManager());
test("security");
LogManager.getLogManager().readConfiguration();
final JavaAWTAccessStub access = new JavaAWTAccessStub();
SharedSecrets.setJavaAWTAccess(access);
test("security and no context");
for (Context ctx : Context.values()) {
LogManager.getLogManager().readConfiguration();
access.setContext(ctx);
test("security and context " + ctx);
}
}
/**
* Release any internal references to previously created {@link LogFactory}
* instances that have been associated with the specified class loader
* (if any), after calling the instance method <code>release()</code> on
* each of them.
*
* @param classLoader ClassLoader for which to release the LogFactory
*/
public static void release(ClassLoader classLoader) {
// JULI's log manager looks at the current classLoader so there is no
// need to use the passed in classLoader, the default implementation
// does not so calling reset in that case will break things
if (!LogManager.getLogManager().getClass().getName().equals(
"java.util.logging.LogManager")) {
LogManager.getLogManager().reset();
}
}
@Override
public void run() {
while (goOn) {
try {
LogManager.getLogManager().readConfiguration();
readCount.incrementAndGet();
Thread.sleep(1);
} catch (Exception x) {
fail(x);
}
}
}
public LogConfig() {
LogManager manager = LogManager.getLogManager();
Logger logger = Logger.getLogger("com.xyz.foo");
if (logger.getHandlers().length > 0) {
System.err.println(this.getClass().getName() + ": "
+ "Unexpected handlers: "
+ List.of(logger.getHandlers()));
throw new RuntimeException("Unexpected handlers: "
+ List.of(logger.getHandlers()));
}
logger.addHandler(new TestHandler());
LOGGERS.add(logger);
}
public static synchronized void doLog() {
if(!doLog) {
doLog = true;
createLogHandler(Config.getTmpDir() + Config.getPathSeparator() + "aesh.log");
for(Enumeration<String> loggerEnum = LogManager.getLogManager().getLoggerNames(); loggerEnum.hasMoreElements(); ) {
Logger logger = LogManager.getLogManager().getLogger(loggerEnum.nextElement());
if (logger != null) {
removeAllHandlers(logger);
logger.addHandler(logHandler);
}
}
}
}
@Test
public void testLogLevelIssueCXF3466() throws Exception {
startServer("Mortimer");
Greeter mortimer = getMortimerGreeter();
Logger rootLogger = LogManager.getLogManager().getLogger("");
Level oldLevel = rootLogger.getLevel();
rootLogger.setLevel(Level.FINE);
try {
// Will throw exception Stream is closed if bug is present
mortimer.sayHi();
} finally {
rootLogger.setLevel(oldLevel);
}
assertProxyRequestCount(1);
}
protected void initMainPanel() {
String tabbed = LogManager.getLogManager().getProperty(isTabbedPropField);
if (tabbed != null && tabbed.equals("true")) {
isTabbed = true;
}
pcenter = new JPanel(new BorderLayout());
if (isTabbed) {
tabPane = new JTabbedPane(JTabbedPane.LEFT);
pcenter.add(BorderLayout.CENTER, tabPane);
}
frame.getContentPane().add(BorderLayout.CENTER, pcenter);
}
/**
* Visible version of {@link java.util.logging.LogManager#getStringProperty(String, String)}.
*
* If the property is not defined we return the given default value.
*/
public static String getStringProperty(@Nonnull LogManager manager, @Nullable String name, String defaultValue) {
if (name == null) {
return defaultValue;
}
String val = manager.getProperty(name);
if (val == null) {
return defaultValue;
}
return val.trim();
}