下面列出了java.util.logging.Logger#getLevel ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void maven_build_jar_project_on_master_with_disabled_publisher_param_succeeds(MavenPublisher.DescriptorImpl descriptor, String symbol, boolean disabled) throws Exception {
Logger logger = Logger.getLogger(MavenSpyLogProcessor.class.getName());
Level level = logger.getLevel();
logger.setLevel(Level.FINE);
try {
String displayName = descriptor.getDisplayName();
Symbol symbolAnnotation = descriptor.getClass().getAnnotation(Symbol.class);
String[] symbols = symbolAnnotation.value();
assertThat(new String[]{symbol}, is(symbols));
loadMavenJarProjectInGitRepo(this.gitRepoRule);
String pipelineScript = "node('master') {\n" +
" git($/" + gitRepoRule.toString() + "/$)\n" +
" withMaven(options:[" + symbol + "(disabled:" + disabled + ")]) {\n" +
" sh 'mvn package verify'\n" +
" }\n" +
"}";
WorkflowJob pipeline = jenkinsRule.createProject(WorkflowJob.class, "build-on-master-" + symbol + "-publisher-disabled-" + disabled);
pipeline.setDefinition(new CpsFlowDefinition(pipelineScript, true));
WorkflowRun build = jenkinsRule.assertBuildStatus(Result.SUCCESS, pipeline.scheduleBuild2(0));
String message = "[withMaven] Skip '" + displayName + "' disabled by configuration";
if (disabled) {
jenkinsRule.assertLogContains(message, build);
} else {
jenkinsRule.assertLogNotContains(message, build);
}
} finally {
logger.setLevel(level);
}
}
/**
* Ctor.
* @param session A Session
* @param src Where the data comes from
* @param lgr A logger
*/
public Logged(
final Session session,
final String src,
final Logger lgr
) {
this.origin = session;
this.source = src;
this.logger = lgr;
this.level = new Unchecked<>(
new Sticky<>(
() -> {
Level lvl = lgr.getLevel();
if (lvl == null) {
Logger parent = lgr;
while (lvl == null) {
parent = parent.getParent();
lvl = parent.getLevel();
}
}
return lvl;
}
)
);
this.connections = new AtomicInteger();
this.statements = new AtomicInteger();
}
@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);
}
/**
* Disable all logging.
*
* @return The original logging level.
*/
public static Level disableLogging() {
Logger logger = Logger.getLogger("");
Level level = logger.getLevel();
logger.setLevel(Level.OFF);
return level;
}
public static Level disableLogging() {
Logger logger = Logger.getLogger("org.apache.uima");
while (logger.getLevel() == null) {
logger = logger.getParent();
}
Level level = logger.getLevel();
logger.setLevel(Level.OFF);
return level;
}
public void testDeletedFileDoesNotReturnInputStream() throws Exception {
final FileObject testFo = FileUtil.createData(root,"testfile.data");
final File testFile = FileUtil.toFile(testFo);
final Logger LOGGER = Logger.getLogger(FileObj.class.getName());
final Handler handler = new Handler() {
@Override
public void publish(LogRecord record) {
if ("FileObj.getInputStream_after_is_valid".equals(record.getMessage())) {
testFile.delete();
}
}
@Override
public void flush() {
}
@Override
public void close() throws SecurityException {
}
};
final Level originalLevel = LOGGER.getLevel();
LOGGER.setLevel(Level.FINEST);
try {
LOGGER.addHandler(handler);
try {
testFo.getInputStream();
assertTrue("Exception not thrown by deleted file getInputStream()", false);
} catch (FileNotFoundException e) {
//pass - expected exception
} finally {
LOGGER.removeHandler(handler);
}
} finally {
LOGGER.setLevel(originalLevel);
}
}
public void testLRUCaching() throws IOException {
FileObject artefact = getSourceFile (FILE_IN_PACKAGE);
Lookup.getDefault().lookup(MockSLQ.class).register(this.srcRoot, new SpecificationVersion("9")); //NOI18N
assertEquals("9", SourceLevelQuery.getSourceLevel(artefact)); //NOI18N
ClassPathProvider cpp = new DefaultClassPathProvider ();
final Logger log = Logger.getLogger(DefaultClassPathProvider.class.getName());
final H h = new H();
final Level origLevel = log.getLevel();
log.setLevel(Level.FINE);
log.addHandler(h);
try {
ClassPath cp = cpp.findClassPath(artefact, JavaClassPathConstants.MODULE_BOOT_PATH);
assertEquals ("DefaultClassPathProvider returned invalid classpath for MODULE_BOOT_PATH with source level 9",
j9.getBootstrapLibraries(),
cp);
List<JavaPlatform> plts = h.getLRU();
assertEquals(1, plts.size());
assertEquals(j9, plts.get(0));
h.reset();
artefact = getSourceFile (FILE_IN_PACKAGE);
cp = cpp.findClassPath(artefact, JavaClassPathConstants.MODULE_BOOT_PATH);
assertEquals ("DefaultClassPathProvider returned invalid classpath for MODULE_BOOT_PATH with source level 9",
j9.getBootstrapLibraries(),
cp);
plts = h.getLRU();
assertEquals(0, plts.size());
} finally {
log.removeHandler(h);
log.setLevel(origLevel);
}
}
private void maven_build_jar_project_on_master_with_globally_disabled_publisher_succeeds(MavenPublisher.DescriptorImpl descriptor) throws Exception {
MavenPublisher publisher = descriptor.clazz.newInstance();
publisher.setDisabled(true);
GlobalPipelineMavenConfig globalPipelineMavenConfig = GlobalPipelineMavenConfig.get();
globalPipelineMavenConfig.setPublisherOptions(Collections.singletonList(publisher));
Logger logger = Logger.getLogger(MavenSpyLogProcessor.class.getName());
Level level = logger.getLevel();
logger.setLevel(Level.FINE);
try {
Symbol symbolAnnotation = descriptor.getClass().getAnnotation(Symbol.class);
String symbol = symbolAnnotation.value()[0];
String displayName = descriptor.getDisplayName();
loadMavenJarProjectInGitRepo(this.gitRepoRule);
String pipelineScript = "node('master') {\n" +
" git($/" + gitRepoRule.toString() + "/$)\n" +
" withMaven() {\n" +
" sh 'mvn package verify'\n" +
" }\n" +
"}";
WorkflowJob pipeline = jenkinsRule.createProject(WorkflowJob.class, "build-on-master-" + symbol + "-publisher-globally-disabled");
pipeline.setDefinition(new CpsFlowDefinition(pipelineScript, true));
WorkflowRun build = jenkinsRule.assertBuildStatus(Result.SUCCESS, pipeline.scheduleBuild2(0));
String message = "[withMaven] Skip '" + displayName + "' disabled by configuration";
jenkinsRule.assertLogContains(message, build);
} finally {
logger.setLevel(level);
globalPipelineMavenConfig.setPublisherOptions((List<MavenPublisher>) null);
}
}
/**
* Returns the effective level of the given logger, searching in the parent loggers if needed.
* This method does not verify if handlers have higher level.
*/
private static Level getEffectiveLevel(Logger logger) {
while (logger != null) {
final Level level = logger.getLevel();
if (level != null) {
return level;
}
logger = logger.getParent();
}
return Level.INFO; // Default value specified by the java.util.logging framework.
}
public static void enableInstances(Logger log, String msg, Level level) {
if (log == null) {
log = Logger.getLogger("TIMER"); // NOI18N
}
log.addHandler(new InstancesHandler(msg, level,2));
if (log.getLevel() == null || log.getLevel().intValue() > level.intValue()) {
log.setLevel(level);
}
}
private void maven_build_jar_project_on_master_with_publisher_configured_both_globally_and_on_the_pipeline_succeeds(MavenPublisher.DescriptorImpl descriptor) throws Exception {
MavenPublisher publisher = descriptor.clazz.newInstance();
publisher.setDisabled(true);
GlobalPipelineMavenConfig globalPipelineMavenConfig = GlobalPipelineMavenConfig.get();
globalPipelineMavenConfig.setPublisherOptions(Collections.singletonList(publisher));
Logger logger = Logger.getLogger(MavenSpyLogProcessor.class.getName());
Level level = logger.getLevel();
logger.setLevel(Level.FINE);
try {
Symbol symbolAnnotation = descriptor.getClass().getAnnotation(Symbol.class);
String symbol = symbolAnnotation.value()[0];
String displayName = descriptor.getDisplayName();
loadMavenJarProjectInGitRepo(this.gitRepoRule);
String pipelineScript = "node('master') {\n" +
" git($/" + gitRepoRule.toString() + "/$)\n" +
" withMaven(options:[" + symbol + "(disabled: true)]) {\n" +
" sh 'mvn package verify'\n" +
" }\n" +
"}";
WorkflowJob pipeline = jenkinsRule.createProject(WorkflowJob.class, "build-on-master-" + symbol + "-publisher-defined-globally-and-in-the-pipeline");
pipeline.setDefinition(new CpsFlowDefinition(pipelineScript, true));
WorkflowRun build = jenkinsRule.assertBuildStatus(Result.SUCCESS, pipeline.scheduleBuild2(0));
jenkinsRule.assertLogContains("[withMaven] WARNING merging publisher configuration defined in the 'Global Tool Configuration' and at the pipeline level is not yet supported. " +
"Use pipeline level configuration for '" + displayName + "'", build);
jenkinsRule.assertLogContains("[withMaven] Skip '" + displayName + "' disabled by configuration", build);
} finally {
logger.setLevel(level);
globalPipelineMavenConfig.setPublisherOptions((List<MavenPublisher>) null);
}
}
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) {
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 fixLevels()
{
LogManager lm = LogManager.getLogManager();
Enumeration<String> e = LogManager.getLogManager().getLoggerNames();
while(e.hasMoreElements())
{
String s = e.nextElement();
Logger m = LogManager.getLogManager().getLogger(s);
if (m != null)
{
if (m.getLevel() == null)
{
String name = s;
while(name.length() > 0)
{
if (log_props.getProperty(name +".level") != null)
{
Level lvl = Level.parse(log_props.getProperty(name +".level"));
logger.fine(String.format("Setting level for %s to %s based on %s", s, lvl, name));
m.setLevel(lvl);
break;
}
else
{
int last_dot = name.lastIndexOf('.');
if (last_dot < 0)
{
break;
}
else
{
name = name.substring(0, last_dot);
}
}
}
}
}
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
if (upnpService == null)
break;
Toast.makeText(this, R.string.searchingLAN, Toast.LENGTH_SHORT).show();
upnpService.getRegistry().removeAllRemoteDevices();
upnpService.getControlPoint().search();
break;
// DOC:OPTIONAL
case 1:
if (upnpService != null) {
Router router = upnpService.get().getRouter();
try {
if (router.isEnabled()) {
Toast.makeText(this, R.string.disablingRouter, Toast.LENGTH_SHORT)
.show();
router.disable();
} else {
Toast.makeText(this, R.string.enablingRouter, Toast.LENGTH_SHORT)
.show();
router.enable();
}
} catch (RouterException ex) {
Toast.makeText(this,
getText(R.string.errorSwitchingRouter) + ex.toString(),
Toast.LENGTH_LONG).show();
ex.printStackTrace(System.err);
}
}
break;
case 2:
Logger logger = Logger.getLogger("org.fourthline.cling");
if (logger.getLevel() != null && !logger.getLevel().equals(Level.INFO)) {
Toast.makeText(this, R.string.disablingDebugLogging, Toast.LENGTH_SHORT).show();
logger.setLevel(Level.INFO);
} else {
Toast.makeText(this, R.string.enablingDebugLogging, Toast.LENGTH_SHORT).show();
logger.setLevel(Level.FINEST);
}
break;
// DOC:OPTIONAL
}
return false;
}
@Test
public void allMethods() {
MetricsProvider provider = new DefaultProvider();
provider.setTaskMetricsCollector(new TaskMetricsCollector() {
@Override
public int getPoolSize() {
return 0;
}
@Override
public int getMaximumPoolSize() {
return 0;
}
@Override
public int getLargestPoolSize() {
return 0;
}
@Override
public int getCurrentTaskCount() {
return 0;
}
@Override
public int getCurrentQueueCount() {
return 0;
}
@Override
public int getCorePoolSize() {
return 0;
}
@Override
public int getActiveCount() {
// TODO Auto-generated method stub
return 0;
}
});
Logger perfLogger = LogManager.getLogManager().getLogger("org.hyperledger.Performance");
Level original = perfLogger.getLevel();
try {
perfLogger.setLevel(Level.ALL);
Handler mockHandler = Mockito.mock(Handler.class);
ArgumentCaptor<LogRecord> argumentCaptor = ArgumentCaptor.forClass(LogRecord.class);
perfLogger.addHandler(mockHandler);
provider.initialize(new Properties());
((DefaultProvider) provider).logMetrics();
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
Mockito.verify(mockHandler, Mockito.atLeast(1)).publish(argumentCaptor.capture());
LogRecord lr = argumentCaptor.getValue();
String msg = lr.getMessage();
assertThat(msg).contains("{ \"active_count\":0 , \"pool_size\":0 , \"core_pool_size\":0 , \"current_task_count\":0 , \"current_queue_depth\":0 ");
} finally {
perfLogger.setLevel(original);
}
}
/** Enables logging for given logger name and given severity.
* Everything logged to the object is going to go to the returned
* CharSequence object which can be used to check the content or
* converted <code>toString</code>.
* <p>
* The logging stops when the returned object is garbage collected.
*
* @param loggerName the name to capture logging for
* @param level the level of details one wants to get
* @return character sequence which can be check or converted to string
* @since 1.27
*/
public static CharSequence enable(String loggerName, Level level) {
IL il = new IL(false);
class MyPs extends PrintStream implements CharSequence {
private ByteArrayOutputStream os;
public MyPs() {
this(new ByteArrayOutputStream());
}
private MyPs(ByteArrayOutputStream arr) {
super(arr);
os = arr;
}
public int length() {
return toString().length();
}
public char charAt(int index) {
return toString().charAt(index);
}
public CharSequence subSequence(int start, int end) {
return toString().subSequence(start, end);
}
@Override
public String toString() {
return os.toString();
}
}
Logger l = Logger.getLogger(loggerName);
if (l.getLevel() == null || l.getLevel().intValue() > level.intValue()) {
l.setLevel(level);
}
MyPs ps = new MyPs();
Log log = new Log(l, ps);
log.setLevel(level);
l.addHandler(log);
return ps;
}
public void testModuleNameCache_ModuleInfoUpdated() throws IOException {
final Logger l = Logger.getLogger(ModuleOraculum.class.getName());
final Level origLogLevel = l.getLevel();
final H h = new H();
l.setLevel(Level.FINE);
l.addHandler(h);
try {
final ClasspathInfo cpInfo = new ClasspathInfo.Builder(ClassPath.EMPTY).build();
final JavacParser parser = new JavacParser(Collections.emptyList(), true);
JavacTaskImpl impl = createJavacTask(
javaFile1,
root1,
cpInfo,
parser,
null,
false);
assertPatchModules(impl, "Test");
List<? extends String> names = h.getModuleNames();
assertEquals(1, names.size());
assertEquals("Test", names.get(0)); //NOI18N
h.reset();
createModule(root1, "TestUpdated");
impl = createJavacTask(
javaFile1,
root1,
cpInfo,
parser,
null,
false);
assertPatchModules(impl, "TestUpdated");
names = h.getModuleNames();
assertEquals(1, names.size());
assertEquals("TestUpdated", names.get(0)); //NOI18N
h.reset();
impl = createJavacTask(
javaFile1,
root1,
cpInfo,
parser,
null,
false);
assertPatchModules(impl, "TestUpdated");
names = h.getModuleNames();
assertEquals(0, names.size());
} finally {
l.removeHandler(h);
l.setLevel(origLogLevel);
}
}
public void testEncodingCaching() throws Exception {
final Logger log = Logger.getLogger(HtmlDataObject.class.getName());
class TestHandler extends Handler {
private final Pattern pattern = Pattern.compile("^HtmlDataObject.getFileEncoding (non)?cached .*$"); //NOI18N
Boolean cached;
@Override
public void publish(LogRecord record) {
final String message = record.getMessage();
final Matcher matcher = pattern.matcher(message);
if (matcher.matches()) {
cached = matcher.group(1) == null ? Boolean.TRUE : Boolean.FALSE;
}
}
@Override
public void flush() {
}
@Override
public void close() throws SecurityException {
}
}
final TestHandler handler = new TestHandler();
log.addHandler(handler);
final Level origLevel = log.getLevel();
log.setLevel(Level.FINEST);
try {
FileObject data = FileUtil.createData (FileUtil.toFileObject(getWorkDir()), "UTF8.html"); //NOI18N
copy("UTF8.html",data); //NOI18N
handler.cached = null;
read(data);
assertFalse("Encoding should be calculated",handler.cached); //NOI18N
handler.cached = null;
read(data);
assertTrue("Encoding should be cached",handler.cached); //NOI18N
//Modify file
copy("UTF8.html",data); //NOI18N
handler.cached = null;
read(data);
assertFalse("Encoding should be calculated",handler.cached); //NOI18N
handler.cached = null;
read(data);
assertTrue("Encoding should be cached",handler.cached); //NOI18N
} finally {
log.setLevel(origLevel);
log.removeHandler(handler);
}
}
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());
}
}