Java Code Examples for java.util.logging.ConsoleHandler

The following examples show how to use java.util.logging.ConsoleHandler. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: Open-Lowcode   Source File: DebugLoggerSetup.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * setup logs that display in a compact way on console
 */
public static void setUpLogsForConsoleDebugging() {
	
	ConsoleHandler consolehandler = new ConsoleHandler();
	consolehandler.setFormatter(new ConsoleFormatter());
	
	Logger anonymouslogger = Logger.getLogger("");
	for (int i = 0; i < anonymouslogger.getHandlers().length; i++) {
		anonymouslogger.removeHandler(anonymouslogger.getHandlers()[i]);
	}
	anonymouslogger.addHandler(consolehandler);
	anonymouslogger.setUseParentHandlers(false);
	anonymouslogger.setLevel(Level.ALL);


	// --------------------------------------------------------------
	Logger rootlogger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
	for (int i = 0; i < rootlogger.getHandlers().length; i++) {
		rootlogger.removeHandler(rootlogger.getHandlers()[i]);
	}
	rootlogger.addHandler(consolehandler);
	rootlogger.setUseParentHandlers(false);
	rootlogger.setLevel(Level.ALL);
}
 
Example 2
Source Project: vjtools   Source File: Client.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
	Client client = new Client();
	// Set the logger to use our all-on-one-line formatter.
	Logger l = Logger.getLogger("");
	Handler[] hs = l.getHandlers();
	for (int i = 0; i < hs.length; i++) {
		Handler h = hs[0];
		if (h instanceof ConsoleHandler) {
			h.setFormatter(client.new OneLineSimpleLogger());
		}
	}
	try {
		client.execute(args);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 3
Source Project: vjtools   Source File: Client.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
	Client client = new Client();
	// Set the logger to use our all-on-one-line formatter.
	Logger l = Logger.getLogger("");
	Handler[] hs = l.getHandlers();
	for (int i = 0; i < hs.length; i++) {
		Handler h = hs[0];
		if (h instanceof ConsoleHandler) {
			h.setFormatter(client.new OneLineSimpleLogger());
		}
	}
	try {
		client.execute(args);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 4
Source Project: redpipe   Source File: AppTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCdiInjection(TestContext context) {
  final ConsoleHandler consoleHandler = new ConsoleHandler();
  consoleHandler.setLevel(Level.FINEST);
  consoleHandler.setFormatter(new SimpleFormatter());

  final Logger app = Logger.getLogger("org.jboss.weld.vertx");
  app.setLevel(Level.FINEST);
  app.addHandler(consoleHandler);

  Async async = context.async();
    webClient.get("/test/injection")
    .as(BodyCodec.string())
    .rxSend()
    .subscribe(body -> {
        context.assertEquals(200, body.statusCode());
        async.complete();
    }, x -> { 
        x.printStackTrace();
        context.fail(x);
        async.complete();
    });
}
 
Example 5
Source Project: component-runtime   Source File: EnvironmentSetup.java    License: Apache License 2.0 6 votes vote down vote up
private static void jul() {
    final Logger root = Logger.getLogger("");
    root.setLevel(Level.SEVERE);
    final Handler[] handlers = root.getHandlers();
    Stream.of(handlers).forEach(root::removeHandler);
    final ConsoleHandler handler = new ConsoleHandler() {

        {
            setFormatter(new UnifiedFormatter());
        }

        @Override
        protected synchronized void setOutputStream(final OutputStream out) throws SecurityException {
            super.setOutputStream(new StdErrStream());
        }
    };
    handler.setLevel(Level.SEVERE);
    root.addHandler(handler);
}
 
Example 6
Source Project: cxf   Source File: JaxrsHeaderPropagationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testHeadersArePropagated() throws Exception {
    Logger logger = 
        Logger.getLogger("org.eclipse.microprofile.rest.client.ext.DefaultClientHeadersFactoryImpl"); //NOPMD
    logger.setLevel(Level.ALL);
    ConsoleHandler h = new ConsoleHandler();
    h.setLevel(Level.ALL);
    logger.addHandler(new ConsoleHandler());
    final Response r = createWebClient("/jaxrs/propagate")
        .header("Header1", "Single")
        .header("MultiHeader", "value1", "value2", "value3")
        .get();
    assertEquals(Status.OK.getStatusCode(), r.getStatus());
    String propagatedHeaderContent = r.readEntity(String.class);
    System.out.println("propagatedHeaderContent: " + propagatedHeaderContent);
    assertTrue(propagatedHeaderContent.contains("Header1=Single"));
    assertTrue(propagatedHeaderContent.contains("MultiHeader=value1,value2,value3"));
}
 
Example 7
Source Project: uavstack   Source File: PLogger.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean enableConsoleOut(boolean check) {

    if (check == true) {
        if (this.consoleHandler == null) {
            this.consoleHandler = new ConsoleHandler();
            this.consoleHandler.setLevel(this.level);
            this.consoleHandler.setFormatter(new DefaultLogFormatter());
        }
        log.addHandler(this.consoleHandler);
        isEnableConsoleOutSus = true;
    }
    else {
        if (this.consoleHandler != null) {
            log.removeHandler(this.consoleHandler);
        }
        isEnableConsoleOutSus = false;
    }
		
    return isEnableConsoleOutSus;
}
 
Example 8
Source Project: blazingcache   Source File: ManagementTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setupLogger() throws Exception {
    Level level = Level.SEVERE;
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            System.err.println("uncaughtException from thread " + t.getName() + ": " + e);
            e.printStackTrace();
        }
    });
    java.util.logging.LogManager.getLogManager().reset();
    ConsoleHandler ch = new ConsoleHandler();
    ch.setLevel(level);
    SimpleFormatter f = new SimpleFormatter();
    ch.setFormatter(f);
    java.util.logging.Logger.getLogger("").setLevel(level);
    java.util.logging.Logger.getLogger("").addHandler(ch);
}
 
Example 9
Source Project: api-mining   Source File: Logging.java    License: GNU General Public License v3.0 6 votes vote down vote up
/** Set up console handler */
public static Handler setUpConsoleHandler() {
	final ConsoleHandler handler = new ConsoleHandler() {
		@Override
		protected void setOutputStream(final OutputStream out) throws SecurityException {
			super.setOutputStream(System.out);
		}
	};
	handler.setLevel(Level.ALL);
	final Formatter formatter = new Formatter() {
		@Override
		public String format(final LogRecord record) {
			return record.getMessage();
		}
	};
	handler.setFormatter(formatter);
	return handler;
}
 
Example 10
Source Project: blazingcache   Source File: IteratorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setupLogger() throws Exception {
    Level level = Level.SEVERE;
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            System.err.println("uncaughtException from thread " + t.getName() + ": " + e);
            e.printStackTrace();
        }
    });
    java.util.logging.LogManager.getLogManager().reset();
    ConsoleHandler ch = new ConsoleHandler();
    ch.setLevel(level);
    SimpleFormatter f = new SimpleFormatter();
    ch.setFormatter(f);
    java.util.logging.Logger.getLogger("").setLevel(level);
    java.util.logging.Logger.getLogger("").addHandler(ch);
}
 
Example 11
/**
 * Main entry point for the OpenOffice.org Remote Write Test.
 *
 * @param args arguments of the test
 *
 * @author Andreas Bröker
 * @date 17.08.2006
 */
public static void main(String[] args) {
  if(args.length < 2) {
    System.out.println("NOA Remote Write Test");
    System.out.println("-------------------");
    System.out.println("Usage:");
    System.out.println("RemoteWriteTest <host> <port>");
  }
  else { 
    LogManager.getLogManager().reset();
    ConsoleHandler consoleHandler = new ConsoleHandler();
    consoleHandler.setLevel(Level.FINEST);
    LOGGER.addHandler(consoleHandler);
    LOGGER.setLevel(Level.FINEST);
    
    try {
      FileHandler fileHandler = new FileHandler("log.xml");
      fileHandler.setLevel(Level.FINEST);
      LOGGER.addHandler(fileHandler);
    }
    catch (Throwable throwable) {
    }
    RemoteWriteTest remoteWriteTest = new RemoteWriteTest();
    remoteWriteTest.test(args[0], args[1]);
  }
}
 
Example 12
Source Project: selenium   Source File: LoggingManager.java    License: Apache License 2.0 5 votes vote down vote up
public static void overrideSimpleFormatterWithTerseOneForConsoleHandler(
  Logger logger,
  boolean debugMode) {
  for (Handler handler : logger.getHandlers()) {
    if (handler instanceof ConsoleHandler) {
      final Formatter formatter;

      formatter = handler.getFormatter();
      if (formatter instanceof SimpleFormatter) {
        final StdOutHandler stdOutHandler;
        final Level originalLevel;

        /*
         * DGF - Nobody likes the SimpleFormatter; surely they wanted our terse formatter instead.
         */
        originalLevel = handler.getLevel();
        handler.setFormatter(new TerseFormatter());
        handler.setLevel(Level.WARNING);

        /*
         * Furthermore, we all want DEBUG/INFO on stdout and WARN/ERROR on stderr
         */
        stdOutHandler = new StdOutHandler();
        stdOutHandler.setFormatter(new TerseFormatter());
        stdOutHandler.setFilter(new MaxLevelFilter(Level.INFO));
        stdOutHandler.setLevel(originalLevel);
        logger.addHandler(stdOutHandler);
        if (debugMode) {
          if (originalLevel.intValue() > Level.FINE.intValue()) {
            stdOutHandler.setLevel(Level.FINE);
          }
        }
      }
    }
  }
}
 
Example 13
private void configureLogging(ManagedSEContainerConfiguration configuration) {
    ConsoleHandler consoleHandler = new ConsoleHandler();
    consoleHandler.setLevel(configuration.getLogLevel());
    LOGGER.setUseParentHandlers(false);
    LOGGER.addHandler(consoleHandler);
    LOGGER.setLevel(configuration.getLogLevel());
}
 
Example 14
Source Project: seppuku   Source File: Seppuku.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Setup a logger and set the format
 */
private void initLogger() {
    this.logger = Logger.getLogger(Seppuku.class.getName());
    logger.setUseParentHandlers(false);
    final ConsoleHandler handler = new ConsoleHandler();
    handler.setFormatter(new SeppukuFormatter());
    logger.addHandler(handler);
}
 
Example 15
Source Project: LicenseScout   Source File: BaseFinderTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Initializes logging.
 * @throws Exception
 */
@BeforeClass
public static void setUpClass() throws Exception {
    Logger.getGlobal().setLevel(Level.FINEST);
    Handler consoleHandler = new ConsoleHandler();
    consoleHandler.setLevel(Level.FINEST);
    Logger.getGlobal().addHandler(consoleHandler);
    TestUtil.setDefaultMessageDigestAlgorithm();
}
 
Example 16
Source Project: TencentKona-8   Source File: DebugLogger.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static Logger instantiateLogger(final String name, final Level level) {
    final Logger logger = java.util.logging.Logger.getLogger(name);
    AccessController.doPrivileged(new PrivilegedAction<Void>() {
        @Override
        public Void run() {
            for (final Handler h : logger.getHandlers()) {
                logger.removeHandler(h);
            }

            logger.setLevel(level);
            logger.setUseParentHandlers(false);
            final Handler c = new ConsoleHandler();

            c.setFormatter(new Formatter() {
                @Override
                public String format(final LogRecord record) {
                    final StringBuilder sb = new StringBuilder();

                    sb.append('[')
                    .append(record.getLoggerName())
                    .append("] ")
                    .append(record.getMessage())
                    .append('\n');

                    return sb.toString();
                }
            });
            logger.addHandler(c);
            c.setLevel(level);
            return null;
        }
    }, createLoggerControlAccCtxt());

    return logger;
}
 
Example 17
static public void setup(String outputDir, Boolean noConsole) throws IOException {
	// get the global logger to configure it
	LogManager.getLogManager().reset();
	log.setLevel(Level.INFO);
	DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
	Date date = new Date();
	File file = new File(outputDir+"/DeconvolutionLog_"+dateFormat.format(date)+".txt");

	File parent = file.getParentFile();
	if (!parent.exists() && !parent.mkdirs()) {
	    throw new IllegalStateException("Couldn't create dir: " + parent);
	}
	
	Files.deleteIfExists(file.toPath());
	
	setOutfilePath(new FileHandler(outputDir+"/DeconvolutionLog_"+dateFormat.format(date)+".txt"));
	CustomRecordFormatter customFormatter = new CustomRecordFormatter();
	ConsoleHandler consoleHandler = new ConsoleHandler();
	consoleHandler.setFormatter(customFormatter);
	outfilePath.setFormatter(customFormatter);
	log.setUseParentHandlers(false);
	if (!noConsole){
		log.addHandler(consoleHandler);
	}
	log.addHandler(outfilePath);

}
 
Example 18
Source Project: jdk8u60   Source File: DebugLogger.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static Logger instantiateLogger(final String name, final Level level) {
    final Logger logger = java.util.logging.Logger.getLogger(name);
    AccessController.doPrivileged(new PrivilegedAction<Void>() {
        @Override
        public Void run() {
            for (final Handler h : logger.getHandlers()) {
                logger.removeHandler(h);
            }

            logger.setLevel(level);
            logger.setUseParentHandlers(false);
            final Handler c = new ConsoleHandler();

            c.setFormatter(new Formatter() {
                @Override
                public String format(final LogRecord record) {
                    final StringBuilder sb = new StringBuilder();

                    sb.append('[')
                       .append(record.getLoggerName())
                       .append("] ")
                       .append(record.getMessage())
                       .append('\n');

                    return sb.toString();
                }
            });
            logger.addHandler(c);
            c.setLevel(level);
            return null;
        }
    }, createLoggerControlAccCtxt());

    return logger;
}
 
Example 19
Source Project: tomee   Source File: RoundRobinConnectionStrategyTest.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 20
Source Project: Ogar2-Server   Source File: OgarServer.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void setupLogging() {
    log.setUseParentHandlers(false);

    LogFormatter formatter = new LogFormatter();

    ConsoleHandler ch = new ConsoleHandler();
    ch.setFormatter(formatter);
    if (isDebugging()) {
        log.setLevel(Level.FINEST);
        ch.setLevel(Level.FINEST);
    } else {
        log.setLevel(Level.INFO);
        ch.setLevel(Level.INFO);
    }
    log.addHandler(ch);

    try {
        FileHandler fh = new FileHandler("server.log");
        fh.setFormatter(formatter);
        if (isDebugging()) {
            fh.setLevel(Level.FINEST);
        } else {
            ch.setLevel(Level.INFO);
        }
        log.addHandler(fh);
    } catch (IOException ex) {
        log.log(Level.SEVERE, "Error while adding FileHandler to logger. Logs will not be output to a file.", ex);
    }

}
 
Example 21
Source Project: nadia   Source File: NadiaProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private void init(){
	init=true;
	startedOn = new Date();
	//format logging
	logger.setUseParentHandlers(false);	 
	CustomFormatter fmt = new CustomFormatter();
	Handler ch = new ConsoleHandler();
	ch.setFormatter(fmt);
	logger.addHandler(ch);
	
	logger.setLevel(Level.INFO);
}
 
Example 22
Source Project: netbeans   Source File: FaceletsLibrarySupportTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
    JsfCustomIndexer.LOGGER.setLevel(Level.FINE);

    Handler h = new ConsoleHandler();
    h.setLevel(Level.FINE);
    JsfCustomIndexer.LOGGER.addHandler(h);
    super.setUp();
}
 
Example 23
@Inject HttpClient(Loggers loggers, HttpClientConfiguration config, JsonUtils jsonUtils, Gson gson) {
    this.logger = loggers.get(getClass());
    this.config = checkNotNull(config, "config");
    this.jsonUtils = jsonUtils;
    this.gson = gson;
    ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("API HTTP Executor").build();
    if (config.getThreads() > 0) {
        this.executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(config.getThreads()));
    } else {
        this.executorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool(threadFactory));
    }

    this.requestFactory = this.createRequestFactory();

    // By default the google http client is very noisy on http errors,
    // spitting out a long stack trace every time one try of a request
    // fails. Disabling the parent handlers (removes default console
    // handling) and adding our own handler that will only show the short
    // message makes the error output much more manageable.
    // See HttpRequest#986 for the offending line and HttpTransport#81 for
    // the logger definition (it's package private so we can't access it
    // directly).
    final Logger httpLogger = Logger.getLogger(HttpTransport.class.getName());
    httpLogger.setUseParentHandlers(false);
    httpLogger.addHandler(new ConsoleHandler() {
        @Override
        public void publish(LogRecord record) {
            String message = record.getMessage();
            if (record.getThrown() != null) message += ": " + record.getThrown().toString();
            HttpClient.this.logger.log(record.getLevel(), message);
        }
    });
}
 
Example 24
Source Project: cas-server-security-filter   Source File: FilterUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void configureLogging(final Handler handler, final Logger logger) {
    for (final Handler h : logger.getHandlers()) {
        logger.removeHandler(h);
    }
    logger.setUseParentHandlers(false);

    if (handler == null) {
        final ConsoleHandler consoleHandler = new ConsoleHandler();
        consoleHandler.setFormatter(new Formatter() {
            @Override
            public String format(final LogRecord record) {
                final StringBuffer sb = new StringBuffer();

                sb.append("[");
                sb.append(record.getLevel().getName());
                sb.append("]\t");

                sb.append(formatMessage(record));
                sb.append("\n");

                return sb.toString();
            }
        });
        logger.addHandler(consoleHandler);
    } else {
        logger.addHandler(handler);
    }

}
 
Example 25
private static Logger instantiateLogger(final String name, final Level level) {
    final Logger logger = java.util.logging.Logger.getLogger(name);
    AccessController.doPrivileged(new PrivilegedAction<Void>() {
        @Override
        public Void run() {
            for (final Handler h : logger.getHandlers()) {
                logger.removeHandler(h);
            }

            logger.setLevel(level);
            logger.setUseParentHandlers(false);
            final Handler c = new ConsoleHandler();

            c.setFormatter(new Formatter() {
                @Override
                public String format(final LogRecord record) {
                    final StringBuilder sb = new StringBuilder();

                    sb.append('[')
                    .append(record.getLoggerName())
                    .append("] ")
                    .append(record.getMessage())
                    .append('\n');

                    return sb.toString();
                }
            });
            logger.addHandler(c);
            c.setLevel(level);
            return null;
        }
    }, createLoggerControlAccCtxt());

    return logger;
}
 
Example 26
public LoggerFinderAPITest(boolean verbose) {
    this.warnDuplicateMappings = verbose;
    for (Handler h : Logger.getLogger("").getHandlers()) {
        if (h instanceof ConsoleHandler) {
            Logger.getLogger("").removeHandler(h);
        }
    }
    Logger.getLogger("").addHandler( new Handler() {
        @Override
        public void publish(LogRecord record) {
            StringBuilder builder = new StringBuilder();
            builder.append("GOT LogRecord: ")
                    .append(record.getLevel().getLocalizedName())
                    .append(": [").append(record.getLoggerName())
                    .append("] ").append(record.getSourceClassName())
                    .append('.')
                    .append(record.getSourceMethodName()).append(" -> ")
                    .append(record.getMessage())
                    .append(' ')
                    .append(record.getParameters() == null ? ""
                            : Arrays.toString(record.getParameters()))
                    ;
            System.out.println(builder);
            if (record.getThrown() != null) {
                record.getThrown().printStackTrace(System.out);
            }
        }
        @Override public void flush() {}
        @Override public void close() {}
    });
}
 
Example 27
Source Project: SB_Elsinore_Server   Source File: BrewServer.java    License: MIT License 5 votes vote down vote up
/**
 * Initialize the logger.  Look at the current logger and its parents to see
 * if it already has a handler setup.  If not, it adds one.
 *
 * @param logger
 *            The logger to initialize
 */
private void initializeLogger(final Logger logger) {
    if (logger.getHandlers().length == 0) {
        if (logger.getParent() != null
                && logger.getUseParentHandlers()) {
            initializeLogger(LOG.getParent());
        } else {
            Handler newHandler = new ConsoleHandler();
            logger.addHandler(newHandler);
        }
    }
}
 
Example 28
Source Project: openjdk-jdk9   Source File: Security.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void initServer() throws Exception {
    String portstring = System.getProperty("port.number");
    port = portstring != null ? Integer.parseInt(portstring) : 0;
    portstring = System.getProperty("port.number1");
    proxyPort = portstring != null ? Integer.parseInt(portstring) : 0;

    Logger logger = Logger.getLogger("com.sun.net.httpserver");
    ConsoleHandler ch = new ConsoleHandler();
    logger.setLevel(Level.ALL);
    ch.setLevel(Level.ALL);
    logger.addHandler(ch);
    String root = System.getProperty ("test.src")+ "/docs";
    InetSocketAddress addr = new InetSocketAddress (port);
    s1 = HttpServer.create (addr, 0);
    if (s1 instanceof HttpsServer) {
        throw new RuntimeException ("should not be httpsserver");
    }
    HttpHandler h = new FileServerHandler (root);
    HttpContext c = s1.createContext ("/files", h);

    HttpHandler h1 = new RedirectHandler ("/redirect");
    HttpContext c1 = s1.createContext ("/redirect", h1);

    executor = Executors.newCachedThreadPool();
    s1.setExecutor (executor);
    s1.start();

    if (port == 0)
        port = s1.getAddress().getPort();
    else {
        if (s1.getAddress().getPort() != port)
            throw new RuntimeException("Error wrong port");
        System.out.println("Port was assigned by Driver");
    }
    System.out.println("HTTP server port = " + port);
    httproot = "http://127.0.0.1:" + port + "/files/";
    redirectroot = "http://127.0.0.1:" + port + "/redirect/";
    uri = new URI(httproot);
    fileuri = httproot + "foo.txt";
}
 
Example 29
Source Project: openjdk-jdk9   Source File: DebugLogger.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static Logger instantiateLogger(final String name, final Level level) {
    final Logger logger = java.util.logging.Logger.getLogger(name);
    AccessController.doPrivileged(new PrivilegedAction<Void>() {
        @Override
        public Void run() {
            for (final Handler h : logger.getHandlers()) {
                logger.removeHandler(h);
            }

            logger.setLevel(level);
            logger.setUseParentHandlers(false);
            final Handler c = new ConsoleHandler();

            c.setFormatter(new Formatter() {
                @Override
                public String format(final LogRecord record) {
                    final StringBuilder sb = new StringBuilder();

                    sb.append('[')
                    .append(record.getLoggerName())
                    .append("] ")
                    .append(record.getMessage())
                    .append('\n');

                    return sb.toString();
                }
            });
            logger.addHandler(c);
            c.setLevel(level);
            return null;
        }
    }, createLoggerControlAccCtxt());

    return logger;
}
 
Example 30
Source Project: alipay-sdk   Source File: AlipayLogger.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 开启DEBUG级别日志(仅针对JDK14LOGGER,LOG4J请自行修改配置文件)
 * 
 * @param isEnabled
 */
public static void setJDKDebugEnabled(Boolean isEnabled) {
    //如果使用JDK14LOGGER,将业务日志级别设为DEBUG(FINE)
    if (blog instanceof Jdk14Logger) {
        Jdk14Logger logger = (Jdk14Logger) blog;
        if (isEnabled) {
            logger.getLogger().setLevel(Level.FINE);
            Handler consoleHandler = new ConsoleHandler();
            consoleHandler.setLevel(Level.FINE);
            logger.getLogger().addHandler(consoleHandler);
        } else {
            logger.getLogger().setLevel(Level.INFO);
        }
    }
}