下面列出了java.util.logging.Logger#setLevel ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Add root logger to root logger list
* 1, add it to root logger list if not exist
* 2, set level
* 3, add handler to it and set use parent handle as false
* There is one root logger in list by default, it's name space is "org.eclipse.birt"
* If there is another root logger need using, invoke this method,
* e.g. the name space of the logger is "com.actuate.birt"
* @param rootLogger
* the root logger need add to list
*
*/
public static void addRootLogger(Logger rootLogger)
{
if( ROOT_LOGGERS.contains( rootLogger ) )
{
return;
}
ROOT_LOGGERS.add( rootLogger );
Level level = ROOT_LOGGERS.get( 0 ).getLevel( );
rootLogger.setLevel( level );
if( adapterHandler != null )
{
rootLogger.addHandler( adapterHandler );
rootLogger.setUseParentHandlers( false );
}
}
@Override
protected void tearDown() throws Exception {
final TestHandler handler = new TestHandler();
final Logger logger = Logger.getLogger(RepositoryUpdater.class.getName()+".tests"); //NOI18N
try {
logger.setLevel (Level.FINEST);
logger.addHandler(handler);
for(String id : registeredClasspaths.keySet()) {
final Map<ClassPath,Void> classpaths = registeredClasspaths.get(id);
GlobalPathRegistry.getDefault().unregister(id, classpaths.keySet().toArray(new ClassPath[classpaths.size()]));
}
handler.await();
} finally {
logger.removeHandler(handler);
}
super.tearDown();
}
private static void logOff(Logger pLogger)
{
pLogger.setLevel(LogConfigurator.OFF);
Handler[] handlers = pLogger.getHandlers();
if(handlers != null){
for(Handler handler : handlers){
pLogger.removeHandler(handler);
}
}
if(pLogger == accessLogger)
{
accessLogEnabled = false;
}
else if(pLogger == logger)
{
logEnabled = false;
}
}
public LoggingConfig() {
try {
// Load a properties file from class path java.util.logging.config.file
final LogManager logManager = LogManager.getLogManager();
URL configURL = getClass().getResource("/logging.properties");
if (configURL != null) {
try (InputStream is = configURL.openStream()) {
logManager.readConfiguration(is);
}
} else {
// Programmatic configuration
System.setProperty("java.util.logging.SimpleFormatter.format",
"%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS.%1$tL %4$-7s [%3$s] %5$s %6$s%n");
final ConsoleHandler consoleHandler = new ConsoleHandler();
consoleHandler.setLevel(Level.FINEST);
consoleHandler.setFormatter(new SimpleFormatter());
final Logger app = Logger.getLogger("app");
app.setLevel(Level.FINEST);
app.addHandler(consoleHandler);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* A method to get and initialize a logger to test for a given class.
*
* @param classToLog the class we want a logger for
* @param level the logging level to enable
* @return the logger
* @throws Exception if something goes wrong
*/
private Logger setupLogger(Class<?> classToLog, Level level) throws Exception {
String loggerName = classToLog.getName();
// Get the logger and assert non-null
Logger l = Logger.getLogger(loggerName);
// Add the verification handler
l.addHandler(handler);
// Set the logging level for the test
l.setLevel(level);
handler.setLevel(level);
return l;
}
private static void set(final Logger logger, final Level level) {
final ConsoleHandler consoleHandler = new ConsoleHandler();
consoleHandler.setLevel(level);
logger.addHandler(consoleHandler);
logger.setLevel(level);
logger.setUseParentHandlers(false);
}
void test3(Logger logger) {
System.out.println("test3: " + loggerName(logger));
AtomicInteger count = new AtomicInteger();
assertEquals(0, TestHandler.PUBLISHED.size(), "Queue should be empty: ");
logger.setLevel(Level.ALL);
assertEquals(0, TestHandler.PUBLISHED.size(), "Queue should be empty: ");
testReflection(logger, count, "severe", "testReflection");
testReflection(logger, count, "warning", "testReflection");
testReflection(logger, count, "info", "testReflection");
testReflection(logger, count, "config", "testReflection");
testReflection(logger, count, "fine", "testReflection");
testReflection(logger, count, "finer", "testReflection");
testReflection(logger, count, "finest", "testReflection");
}
private static void initKeyHook(){
try {
Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
logger.setLevel(Level.WARNING);
logger.setUseParentHandlers(false);
GlobalScreen.setEventDispatcher(new VoidDispatchService());
GlobalScreen.registerNativeHook();
GlobalScreen.addNativeKeyListener(new GlobalKeyListener());
}
catch (Exception ex) {
ex.printStackTrace();
}
}
public BaseQQWindowContext(File point) throws AWTException, IOException, NativeHookException {
robot = new Robot();
pImage = ImageIO.read(point);
WindowHandleTask wintask = new WindowHandleTask(this, map, robot);
Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(wintask, checkInterval, checkInterval,
TimeUnit.SECONDS);
Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
logger.setLevel(Level.OFF);
logger.setUseParentHandlers(false);
GlobalScreen.registerNativeHook();
GlobalScreen.addNativeKeyListener(new GlobalKeyListener());
}
public static void enableLogging()
{
// example code to turn on ALL logging
//
// To see logging:
// [a] set the handler's level
// [b] add the handler
// [c] set the logger's level
Logger l = EasyLinearEquation.getLogger();
Handler lh = new ConsoleHandler();
lh.setFormatter(oneLineFormatter());
// don't forget to do this:
lh.setLevel(Level.ALL);
// alternative: write log to file:
//lh = new FileHandler("log.txt");
// need this too:
l.addHandler(lh);
// and this:
l.setLevel(Level.ALL);
if (EasyLinearEquation.getLogger().isLoggable(Level.FINE))
{
System.out.println("ok");
EasyLinearEquation.getLogger().fine("Hi there");
}
else
{
System.out.println("failed");
}
}
public void unregister() {
for (Logger logger : registeredLoggers) {
logger.setLevel(null);
logger.removeHandler(this);
logger.setUseParentHandlers(true);
}
registeredLoggers.clear();
}
/**
* Un-register {@link Handler log handler} from the list of root loggers.
*/
private void unregisterLogHandler() {
for (final Logger root : getRootLoggers()) {
root.setLevel(logLevelMap.get(root));
root.removeHandler(getLogHandler());
}
logHandler = null;
}
public static void main(String... args) throws Exception {
// Increate the logging level for networking...
System.out.println("Setting logging to max");
Logger networkLog = Logger.getLogger("com.jme3.network");
networkLog.setLevel(Level.FINEST);
// And we have to tell JUL's handler also
// turn up logging in a very convoluted way
Logger rootLog = Logger.getLogger("");
if( rootLog.getHandlers().length > 0 ) {
rootLog.getHandlers()[0].setLevel(Level.FINEST);
}
// Note: in JME 3.1 this is generally unnecessary as the server will
// send a message with all server-registered classes.
// TestChatServer.initializeClasses();
// Leaving the call commented out to be illustrative regarding the
// common old pattern.
// Grab a host string from the user
String s = getString(null, "Host Info", "Enter chat host:", "localhost");
if (s == null) {
System.out.println("User cancelled.");
return;
}
// Register a shutdown hook to get a message on the console when the
// app actually finishes
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.out.println("Chat client is terminating.");
}
});
TestChatClient test = new TestChatClient(s);
test.setVisible(true);
}
@Override
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
boolean isDebugOn = Boolean.parseBoolean(Platform.getDebugOption(TRACE_ID));
if (isDebugOn) {
Logger tm4eCoreLogger = Logger.getLogger("org.eclipse.tm4e");
tm4eCoreLogger.setLevel(Level.FINEST);
tm4eCoreLogger.addHandler(new Handler() {
@Override public void publish(LogRecord record) {
TMUIPlugin.getDefault().getLog().log(new Status(
toSeverity(record.getLevel()),
"org.eclipse.tm4e.core",
record.getMessage()
));
}
private int toSeverity(Level level) {
if (level.intValue() >= Level.SEVERE.intValue()) {
return IStatus.ERROR;
}
if (level.intValue() >= Level.WARNING.intValue()) {
return IStatus.WARNING;
}
return IStatus.INFO;
}
@Override public void flush() {
// nothing to do
}
@Override public void close() throws SecurityException {
// nothing to do
}
});
}
}
@Override
public void onCreate() {
super.onCreate();
Logger logger = Logger.getLogger("hue.dplugin");
if (BuildConfig.DEBUG) {
AndroidHandler handler = new AndroidHandler(logger.getName());
handler.setFormatter(new SimpleFormatter());
handler.setLevel(Level.ALL);
logger.addHandler(handler);
logger.setLevel(Level.ALL);
} else {
logger.setLevel(Level.OFF);
}
}
@Test
public void run() throws Exception {
Assume.assumeTrue( RabbitMqTestUtils.checkRabbitMqIsRunning());
// Prepare karaf container
Option[] options = super.config();
ExamSystem system = PaxExamRuntime.createServerSystem( options );
TestContainer container = PaxExamRuntime.createContainer( system );
Assert.assertEquals( KarafTestContainer.class, container.getClass());
try {
// Start the DM's distribution... and wait... :(
container.start();
ItUtils.waitForDmRestServices( getCurrentPort());
// The console may take time to be ready
Thread.sleep( 4000 );
// Get Karaf directory by Java reflection.
File karafDirectory = TestUtils.getInternalField( container, "targetFolder", File.class );
Assert.assertNotNull( karafDirectory );
File binDirectory = new File( karafDirectory, "bin" );
Assert.assertTrue( binDirectory.exists());
Logger execLogger = Logger.getLogger( getClass().getName());
LogManager.getLogManager().addLogger( execLogger );
execLogger.setLevel( Level.ALL );
final StringHandler logHandler = new StringHandler();
execLogger.addHandler( logHandler );
// Targets list
Map<String,String> targets = new HashMap<> ();
targets.put( "roboconf:target in-memory", "Roboconf :: Target :: In-Memory" );
targets.put( "roboconf:target openstack", "Roboconf :: Target :: Openstack IaaS" );
targets.put( "roboconf:target aws", "Roboconf :: Target :: EC2 IaaS" );
targets.put( "roboconf:target docker", "Roboconf :: Target :: Docker" );
targets.put( "roboconf:target embedded", "Roboconf :: Target :: Embedded" );
targets.put( "roboconf:target azure", "Roboconf :: Target :: Azure IaaS" );
targets.put( "roboconf:target occi", "Roboconf :: Target :: OCCI" );
// Verify if all targets are deployed
for( String target : targets.keySet() ) {
this.logger.info( "Installing " + target + "..." );
List<String> command = new ArrayList<> ();
command.add( "/bin/sh" );
command.add( "client" );
command.add( target );
int code = ProgramUtils.executeCommand( execLogger, command, binDirectory, null, null, null );
if( code != 0 ) {
System.out.println( "\n\n\n" + logHandler.getLogs() + "\n\n\n" );
}
Assert.assertEquals( "Handler for " + target + " failed to be deployed.", 0, code );
Assert.assertFalse(
"Handler for " + target + " failed to be deployed (exec).",
logHandler.getLogs().contains( "Error" ));
}
// Verify if all targets are in bundle list
List<String> cmd = new ArrayList<> ();
cmd.add( "/bin/sh" );
cmd.add( "client" );
cmd.add( "bundle:list" );
int c = ProgramUtils.executeCommand( execLogger, cmd, binDirectory, null, null, null );
Assert.assertEquals( 0, c );
for( String value : targets.values() ) {
Assert.assertTrue( logHandler.getLogs().contains( value ) );
}
} finally {
container.stop();
}
}
@Override
public void run() {
try {
handler.setLevel(Level.FINEST);
while (goOn) {
Logger l;
Logger foo = Logger.getLogger("foo");
Logger bar = Logger.getLogger("foo.bar");
for (long i=0; i < nextLong.longValue() + 100 ; i++) {
if (!goOn) break;
l = Logger.getLogger("foo.bar.l"+i);
final ResourceBundle b = l.getResourceBundle();
final String name = l.getResourceBundleName();
if (b != null) {
if (!name.equals(b.getBaseBundleName())) {
throw new RuntimeException("Unexpected bundle name: "
+b.getBaseBundleName());
}
}
Logger ll = Logger.getLogger(l.getName()+".bie.bye");
ResourceBundle hrb;
String hrbName;
if (handler.getLevel() != Level.FINEST) {
throw new RuntimeException("Handler level is not finest: "
+ handler.getLevel());
}
final int countBefore = handler.count;
handler.reset();
ll.setLevel(Level.FINEST);
ll.addHandler(handler);
ll.log(Level.FINE, "dummy {0}", this);
ll.removeHandler(handler);
final int countAfter = handler.count;
if (countBefore == countAfter) {
throw new RuntimeException("Handler not called for "
+ ll.getName() + "("+ countAfter +")");
}
hrb = handler.rb;
hrbName = handler.rbName;
if (name != null) {
// if name is not null, then it implies that it
// won't change, since setResourceBundle() cannot
// replace a non null name.
// Since we never set the resource bundle on 'll',
// then ll must inherit its resource bundle [name]
// from l - and therefor we should find it in
// handler.rb/handler.rbName
if (!name.equals(hrbName)) {
throw new RuntimeException("Unexpected bundle name: "
+hrbName);
}
// here we know that hrbName is not null so hrb
// should not be null either.
if (!name.equals(hrb.getBaseBundleName())) {
throw new RuntimeException("Unexpected bundle name: "
+hrb.getBaseBundleName());
}
}
// Make sure to refer to 'l' explicitly in order to
// prevent eager garbage collecting before the end of
// the test (JDK-8030192)
if (!ll.getName().startsWith(l.getName())) {
throw new RuntimeException("Logger " + ll.getName()
+ "does not start with expected prefix "
+ l.getName());
}
getRBcount.incrementAndGet();
if (!goOn) break;
Thread.sleep(1);
}
}
} catch (Exception x) {
fail(x);
}
}
public void testEmbeddingIndexerQueryOnInnerOnly() throws Exception {
RepositoryUpdater ru = RepositoryUpdater.getDefault();
assertEquals(0, ru.getScannedBinaries().size());
assertEquals(0, ru.getScannedBinaries().size());
assertEquals(0, ru.getScannedUnknowns().size());
final RepositoryUpdaterTest.TestHandler handler = new RepositoryUpdaterTest.TestHandler();
final Logger logger = Logger.getLogger(RepositoryUpdater.class.getName()+".tests");
logger.setLevel (Level.FINEST);
logger.addHandler(handler);
srcCp = ClassPath.getClassPath(srcRoot, PATH_TOP_SOURCES);
assertNotNull(srcCp);
assertEquals(1, srcCp.getRoots().length);
assertEquals(srcRoot, srcCp.getRoots()[0]);
globalPathRegistry_register(PATH_TOP_SOURCES, srcCp);
assertTrue (handler.await());
assertEquals(0, handler.getBinaries().size());
assertEquals(1, handler.getSources().size());
assertEquals(srcRoot.toURL(), handler.getSources().get(0));
QuerySupport sup;
Collection<? extends IndexResult> res;
Map<? extends Integer,? extends Integer> count;
//Symulate EditorRegistry
final Source src = Source.create(srcFile);
ParserManager.parse(Collections.<Source>singleton(src), new UserTask() {
@Override
public void run(ResultIterator resultIterator) throws Exception {
}
});
final DataObject dobj = DataObject.find(srcFile);
final EditorCookie ec = dobj.getLookup().lookup(EditorCookie.class);
final StyledDocument doc = ec.openDocument();
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
final JEditorPane jp = new JEditorPane() {
@Override
public boolean isFocusOwner() {
return true;
}
};
jp.setDocument(doc);
EditorApiPackageAccessor.get().register(jp);
}
});
//Do modification
NbDocument.runAtomic(doc, new Runnable() {
@Override
public void run() {
try {
doc.insertString(doc.getLength(), "<C>", null); //NOI18N
} catch (Exception e) {
Exceptions.printStackTrace(e);
}
}
});
//Query should be updated
sup = QuerySupport.forRoots(InnerIndexer.NAME, InnerIndexer.VERSION, srcRoot);
res = sup.query("_sn", srcFile.getNameExt(), QuerySupport.Kind.EXACT, (String[]) null);
assertEquals(5,res.size());
count = countModes(res);
assertEquals(Integer.valueOf(1), count.get(0));
assertEquals(Integer.valueOf(2), count.get(1));
assertEquals(Integer.valueOf(1), count.get(2));
assertEquals(Integer.valueOf(1), count.get(3));
}
public static void main(String[] args) {
System.setSecurityManager(new SecurityManager());
Logger anonymous = Logger.getAnonymousLogger();
final TestHandler handler = new TestHandler();
final TestFilter filter = new TestFilter();
final ResourceBundle bundle = ResourceBundle.getBundle(TestBundle.class.getName());
anonymous.setLevel(Level.FINEST);
anonymous.addHandler(handler);
anonymous.setFilter(filter);
anonymous.setUseParentHandlers(true);
anonymous.setResourceBundle(bundle);
if (anonymous.getLevel() != Level.FINEST) {
throw new RuntimeException("Unexpected level: " + anonymous.getLevel());
} else {
System.out.println("Got expected level: " + anonymous.getLevel());
}
if (!Arrays.asList(anonymous.getHandlers()).contains(handler)) {
throw new RuntimeException("Expected handler not found in: "
+ Arrays.asList(anonymous.getHandlers()));
} else {
System.out.println("Got expected handler in: " + Arrays.asList(anonymous.getHandlers()));
}
if (anonymous.getFilter() != filter) {
throw new RuntimeException("Unexpected filter: " + anonymous.getFilter());
} else {
System.out.println("Got expected filter: " + anonymous.getFilter());
}
if (!anonymous.getUseParentHandlers()) {
throw new RuntimeException("Unexpected flag: " + anonymous.getUseParentHandlers());
} else {
System.out.println("Got expected flag: " + anonymous.getUseParentHandlers());
}
if (anonymous.getResourceBundle() != bundle) {
throw new RuntimeException("Unexpected bundle: " + anonymous.getResourceBundle());
} else {
System.out.println("Got expected bundle: " + anonymous.getResourceBundle());
}
try {
anonymous.setParent(Logger.getLogger("foo.bar"));
throw new RuntimeException("Expected SecurityException not raised!");
} catch (SecurityException x) {
System.out.println("Got expected exception: " + x);
}
if (anonymous.getParent() != Logger.getLogger("")) {
throw new RuntimeException("Unexpected parent: " + anonymous.getParent());
} else {
System.out.println("Got expected parent: " + anonymous.getParent());
}
}
public static void main(String[] args) throws Exception
{
// Configure logging
LogManager.getLogManager().readConfiguration(PVASettings.class.getResourceAsStream("/pva_logging.properties"));
final Logger root = Logger.getLogger("");
// Profiler shows blocking in ConsoleHandler,
// so reduce log messages to only warnings for performance tests
root.setLevel(Level.WARNING);
for (Handler handler : root.getHandlers())
handler.setLevel(root.getLevel());
// Start PVA server
final PVAServer server = new PVAServer();
final PVATimeStamp time = new PVATimeStamp();
final PVADouble value = new PVADouble("value", 3.13);
final PVAStructure data = new PVAStructure("demo", "demo_t",
value,
time);
final ServerPV pv = server.createPV("demo", data);
final Semaphore gotit = new Semaphore(0);
ForkJoinPool.commonPool().submit(() ->
{
while (true)
{
// When monitor received a value...
gotit.acquire();
value.set(value.get() + 1);
time.set(Instant.now());
pv.update(data);
}
});
// PVA Client
final PVAClient pva = new PVAClient();
final PVAChannel ch1 = pva.getChannel("demo");
ch1.connect().get();
final AtomicInteger updates = new AtomicInteger();
final MonitorListener listener = (ch, changes, overruns, received) ->
{
updates.incrementAndGet();
// System.out.println(ch.getName() + " = " + received.get("value") + " " + overruns);
gotit.release();
};
ch1.subscribe("", listener );
while (true)
{
TimeUnit.SECONDS.sleep(1);
System.out.println(updates.getAndSet(0) + " loops per second");
}
}