下面列出了java.util.logging.Logger#getLogger ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 初始化全局Logger
*
* @return
*/
private static void initGlobalLog(String logPath) {
// 获取Log
Logger log = Logger.getLogger(LOG_NAME);
// 为log设置全局等级
log.setLevel(Level.ALL);
Handler[] hs = log.getHandlers();
for (Handler h : hs) {
h.close();
log.removeHandler(h);
}
// 添加控制台handler
//LogUtil.addConsoleHandler(log, Level.INFO);
// 添加文件输出handler
LogUtil.addFileHandler(log, Level.INFO, logPath);
// 设置不适用父类的handlers,这样不会在控制台重复输出信息
log.setUseParentHandlers(false);
globalLog = log;
}
@Override
protected void setUp() throws Exception {
System.out.println("### "+getName()+" ###");
if (log == null) {
log = Logger.getLogger(TestKit.LOGGER_NAME);
log.setLevel(Level.ALL);
TestKit.removeHandlers(log);
} else {
TestKit.removeHandlers(log);
}
}
@Override
public Collection<LoggerInfo> getAllLoggers() {
LogManager manager = LogManager.getLogManager();
Logger root = manager.getLogger("");
Map<String,LoggerInfo> map = new HashMap<>();
Enumeration<String> names = manager.getLoggerNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
Logger logger = Logger.getLogger(name);
if( logger == root) {
continue;
}
map.put(name, new JulInfo(name, logger));
while (true) {
int dot = name.lastIndexOf(".");
if (dot < 0)
break;
name = name.substring(0, dot);
if(!map.containsKey(name)) {
map.put(name, new JulInfo(name, null));
}
}
}
map.put(LoggerInfo.ROOT_NAME, new JulInfo(LoggerInfo.ROOT_NAME, root));
return map.values();
}
@Override
protected void setUp() throws Exception {
System.out.println("### "+getName()+" ###");
if (log == null) {
log = Logger.getLogger(TestKit.LOGGER_NAME);
log.setLevel(Level.ALL);
TestKit.removeHandlers(log);
} else {
TestKit.removeHandlers(log);
}
}
public void perRaceDriverInit(DriverThread dt) {
super.perRaceDriverInit(dt);
// - allocate a new dummy Logger without a ResourceBundle;
// this gives the racing threads less to do
// - reset the counters
dummy = Logger.getLogger(LOGGER_PREFIX + getLoopCnt());
iaeCnt.set(0);
worksCnt.set(0);
}
public static void main(String[] args) throws IOException {
System.out.println("Creating loggers.");
// These loggers will be created in the default user context.
final Logger foo1 = Logger.getLogger( "foo" );
final Logger bar1 = Logger.getLogger( "foo.bar" );
if (bar1.getParent() != foo1) {
throw new RuntimeException("Parent logger of bar1 "+bar1+" is not "+foo1);
}
System.out.println("bar1.getParent() is the same as foo1");
// Set a security manager
System.setSecurityManager(new SecurityManager());
System.out.println("Now running with security manager");
// Triggers the creation of the main AppContext
ByteArrayInputStream is = new ByteArrayInputStream(new byte[] { 0, 1 });
ImageIO.read(is); // triggers calls to system loggers & creation of main AppContext
// verify that we're still using the default user context
final Logger bar2 = Logger.getLogger( "foo.bar" );
if (bar1 != bar2) {
throw new RuntimeException("bar2 "+bar2+" is not the same as bar1 "+bar1);
}
System.out.println("bar2 is the same as bar1");
if (bar2.getParent() != foo1) {
throw new RuntimeException("Parent logger of bar2 "+bar2+" is not foo1 "+foo1);
}
System.out.println("bar2.getParent() is the same as foo1");
final Logger foo2 = Logger.getLogger("foo");
if (foo1 != foo2) {
throw new RuntimeException("foo2 "+foo2+" is not the same as foo1 "+foo1);
}
System.out.println("foo2 is the same as foo1");
System.out.println("Test passed.");
}
public BadLogManagerImpl() {
// The call below should generate an NPE, which will be
// catched in LogManager initializer.
globalLogger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
System.err.println("Global is: " + globalLogger);
throw new Error("Should not have reached here");
}
ServerImpl (
HttpServer wrapper, String protocol, InetSocketAddress addr, int backlog
) throws IOException {
this.protocol = protocol;
this.wrapper = wrapper;
this.logger = Logger.getLogger ("com.sun.net.httpserver");
ServerConfig.checkLegacyProperties (logger);
https = protocol.equalsIgnoreCase ("https");
this.address = addr;
contexts = new ContextList();
schan = ServerSocketChannel.open();
if (addr != null) {
ServerSocket socket = schan.socket();
socket.bind (addr, backlog);
bound = true;
}
selector = Selector.open ();
schan.configureBlocking (false);
listenerKey = schan.register (selector, SelectionKey.OP_ACCEPT);
dispatcher = new Dispatcher();
idleConnections = Collections.synchronizedSet (new HashSet<HttpConnection>());
allConnections = Collections.synchronizedSet (new HashSet<HttpConnection>());
reqConnections = Collections.synchronizedSet (new HashSet<HttpConnection>());
rspConnections = Collections.synchronizedSet (new HashSet<HttpConnection>());
time = System.currentTimeMillis();
timer = new Timer ("server-timer", true);
timer.schedule (new ServerTimerTask(), CLOCK_TICK, CLOCK_TICK);
if (timer1Enabled) {
timer1 = new Timer ("server-timer1", true);
timer1.schedule (new ServerTimerTask1(),TIMER_MILLIS,TIMER_MILLIS);
logger.config ("HttpServer timer1 enabled period in ms: "+TIMER_MILLIS);
logger.config ("MAX_REQ_TIME: "+MAX_REQ_TIME);
logger.config ("MAX_RSP_TIME: "+MAX_RSP_TIME);
}
events = new LinkedList<Event>();
logger.config ("HttpServer created "+protocol+" "+ addr);
}
public TestLogger(String loggerName, String className) {
Logger l = null;
try {
l = Logger.getLogger(loggerName);
} catch (Exception x) {
// OK. Should not happen
}
logger = l;
this.className=className;
}
private void setupLogger(final String name) {
Logger logger = Logger.getLogger(name);
if (BuildConfig.DEBUG) {
AndroidHandler handler = new AndroidHandler(logger.getName());
handler.setFormatter(new SimpleFormatter());
handler.setLevel(Level.ALL);
logger.addHandler(handler);
logger.setLevel(Level.ALL);
logger.setUseParentHandlers(false);
} else {
logger.setLevel(Level.OFF);
logger.setFilter((record) -> false);
}
}
@Override
protected void setUp() throws Exception {
System.out.println("### " + getName() + " ###");
if (log == null) {
log = Logger.getLogger(TestKit.LOGGER_NAME);
log.setLevel(Level.ALL);
TestKit.removeHandlers(log);
} else {
TestKit.removeHandlers(log);
}
}
/**
* All the top level beans, sql manager, connection manage, db manager, etc, will be initialized here.
*/
public void afterPropertiesSet() throws Exception
{
configureLogging();
Logger logger = Logger.getLogger(this.getClass().getName());
logger.info("Setup afterPropertiesSet.");
logger.info("Loading JDBC Drivers");
if(this.jdbcDriver!=null)
{
DriverManager.setLoginTimeout(60);
logger.info("Set JDBC DriverManager loginTimeout as 60 seconds");
for(Map.Entry<String, String> e: jdbcDriver.entrySet())
{
logger.info("Loading "+e.getKey()+": "+e.getValue());
try
{
Class.forName(e.getValue());
logger.info("Loaded "+e.getKey()+": "+e.getValue());
}catch(Throwable ex)
{
logger.info("Failed to Load "+e.getKey()+": "+e.getValue());
}
}
}
alertRootPath = new File(new File(this.fileReposirtoryPath), "alerts");
alertRootPath.mkdirs();
this.sqlManager.setSqlPath(sqlPath);
this.sqlManager.init();
this.metricsDef.init();
logger.info("Refreshing metrics list ...");
refreshMetricsList();
logger.info("Retrieved metrics list: " + this.metricsList.size());
this.metaDb.setDbkey(this.configRepKey);
this.metaDb.init();
this.dbInfoManager.setMetaDb(metaDb);//since we store db info now in metricsdb,
//it can only be initialized after metricsDB initialized
this.userManager.setMetaDb(metaDb);
this.auth.setContext(this);
this.queryEngine.setSqlManager(this.sqlManager);
this.queryEngine.setFrameworkContext(this);
this.statDefManager.init();
logger.info("Initialize AutoScanner ...");
this.myperfConfig.init(this);
this.snmpSettings.init(this);
if(this.myperfConfig.isConfigured())
{
this.initMetricsDB(); //move metrics db creation and initialization away from scanner
this.alertSettings.setContext(this);
if(this.metricDb != null)
{
this.dbInfoManager.init(this.metricDb);//need metricsDB to update
this.metricsDef.getUdmManager().loadSubscriptions(this);
this.metricDb.loadAlertSetting(this.alertSettings);//load alert setting after DB info is loaded.
}
}
this.instanceStatesManager.init(this);
this.hipchat.init(this);
autoScanner = new AutoScanner(this);
autoScanner.init();//it will update metricsDB
if(autoScanner.isInitialized())
{
logger.info("Starting AutoScanner ...");
autoScanner.start();
}
logger.info("Done setup afterPropertiesSet.");
}
@Produces
public Logger getLogger(InjectionPoint p) {
return Logger.getLogger(p.getMember().getDeclaringClass().getName());
}
protected @Override void setUp() throws Exception {
clearWorkDir();
System.setProperty ("netbeans.user", getWorkDirPath());
LOG = Logger.getLogger("TEST-" + getName());
}
public RecursiveListenerOnOffTest(String name) {
super(name);
LOG = Logger.getLogger("TEST." + name);
}
public Logger getLogger(String loggerName,String bundleName) {
return Logger.getLogger(loggerName, bundleName);
}
private static Logger createFallbackLogger() {
final Logger fallbackLogger = Logger.getLogger("org.webrtc.Logging");
fallbackLogger.setLevel(Level.ALL);
return fallbackLogger;
}
public Log(Class clazz) {
this.clazz = clazz;
this.className = clazz.getName();
logger = Logger.getLogger(clazz.getName());
logger.setLevel(Level.SEVERE);
}
@Produces
public Logger getLogger(InjectionPoint p) {
return Logger.getLogger(p.getMember().getDeclaringClass().getName());
}
public static void main(String[] args) throws Exception {
final String testCase = args.length == 0 ? "getLogger" : args[0];
final JavaAWTAccessStub access = new JavaAWTAccessStub();
SharedSecrets.setJavaAWTAccess(access);
final ThreadGroup tg = new ThreadGroup("TestGroup");
Thread t = new Thread(tg, "test") {
public void run() {
try {
access.setContext(Context.ONE);
final PrintStream out = System.out;
System.setOut(null);
try {
if ("getLogger".equals(testCase)) {
Logger.getLogger("sun.plugin");
} else {
LogManager.getLogManager();
}
} finally {
System.setOut(out);
}
System.out.println(Logger.global);
} catch (Throwable x) {
x.printStackTrace();
thrown = x;
}
}
};
Policy.setPolicy(new Policy() {
public boolean implies(ProtectionDomain domain,
Permission permission) {
return true; // all permissions
}
});
System.setSecurityManager(new SecurityManager());
t.start();
t.join();
if (thrown == null) {
System.out.println("PASSED: " + testCase);
} else {
System.err.println("FAILED: " + testCase);
throw new Error("Test failed: " + testCase + " - " + thrown, thrown);
}
}