Java Code Examples for java.util.logging.Handler#setFormatter()

The following examples show how to use java.util.logging.Handler#setFormatter() . 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 File: Client.java    From vjtools with 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 2
Source File: LogFilterHandler.java    From org.openntf.domino with Apache License 2.0 6 votes vote down vote up
private void setUpHandler(final Map.Entry<LogConfig.L_LogHandler, L_HandlerEx> handlerEnt,
		final Map.Entry<LogConfig.L_LogHandler, L_HandlerEx> oldHandlerEnt) throws Exception {
	if (oldHandlerEnt != null) {
		if (tryUpdateHandler(handlerEnt, oldHandlerEnt)) {
			return;
		}
	}
	LogConfig.L_LogHandler handlerCfgEnt = handlerEnt.getKey();
	boolean useDefaultFormatter = (handlerCfgEnt._formatterClass == null);
	try {
		Handler newHandler = (Handler) handlerCfgEnt._handlerGetInstance.invoke(null, handlerCfgEnt._handlerConfig,
				useDefaultFormatter);
		handlerEnt.setValue(new L_HandlerEx(newHandler));
		if (!useDefaultFormatter) {
			newHandler.setFormatter((Formatter) handlerCfgEnt._formatterGetInstance.invoke(null));
		}
	} catch (Exception e) {
		System.err.println("Logging: Error setting up Handler " + handlerCfgEnt._handlerClassName);
		throw e;
	}
}
 
Example 3
Source File: RunSourceParser.java    From cplus-libparser with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static void main( String[] args ) {

    Handler consoleHandler = new ConsoleLogger();
    consoleHandler.setLevel(Level.ALL);
    consoleHandler.setFormatter(new LogFormatter("%1$tl:%1$tM:%1$tS [%4$7s] %2$s: %5$s%n"));
    
    Enumeration<String> loggerNames = LogManager.getLogManager().getLoggerNames();
    while (loggerNames.hasMoreElements()) {
        String name = (String) loggerNames.nextElement();
        Logger logger = Logger.getLogger(name);
        logger.setLevel(consoleHandler.getLevel());
        for(Handler handler : logger.getHandlers()) {
          logger.removeHandler(handler);
        }
        logger.addHandler(consoleHandler);
    }
    

//        new SourceParser().parse(new File("/media/Dados/Codigos/Java/Projetos/OpenDevice/opendevice-hardware-libraries/arduino/OpenDevice/DeviceConnection.h"));
//        new SourceParser().parse(new File("/media/Dados/Codigos/Java/Projetos/OpenDevice/opendevice-hardware-libraries/arduino/OpenDevice/DeviceManager.h"));
        new SourceParser().parse(new File("/media/Dados/Codigos/Java/Projetos/OpenDevice/opendevice-hardware-libraries/arduino/OpenDevice/OpenDevice.h"));
//        new SourceParser().parse(new File("/home/ricardo/Documentos/arduino-1.0.6/libraries/Ethernet/examples/AdvancedChatServer/AdvancedChatServer.ino"));
//        new SourceParser().parse(new File("/media/Dados/Programacao/arduino-1.5.8/hardware/arduino/avr/cores/arduino/Arduino.h"));
//        new SourceParser().parse(new File("/media/Dados/Programacao/arduino-src/hardware/arduino/avr/cores/arduino/HardwareSerial.h"));
//        new SourceParser().parse(new File("/media/Dados/Programacao/arduino-1.5.8/hardware/arduino/avr/cores/arduino/USBCore.h"));
    }
 
Example 4
Source File: JmeSystem.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static void initialize(AppSettings settings) {
    if (initialized) {
        return;
    }

    initialized = true;
    try {
        JmeFormatter formatter = new JmeFormatter();

        Handler consoleHandler = new AndroidLogHandler();
        consoleHandler.setFormatter(formatter);
    } catch (SecurityException ex) {
        logger.log(Level.SEVERE, "Security error in creating log file", ex);
    }
    logger.log(Level.INFO, "Running on {0}", getFullName());
}
 
Example 5
Source File: ExecutionLogger.java    From jatecs with GNU General Public License v3.0 5 votes vote down vote up
public ExecutionLogger() {
    super(ExecutionLogger.class.getName(), null);

    Handler h = new ConsoleHandler();
    h.setFormatter(new StatusOutputFormatter());
    addHandler(h);
    setUseParentHandlers(false);
    setLevel(Level.INFO);
}
 
Example 6
Source File: TomcatTestServer.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public void enableLogging(final Level level) {
  tomcat.setSilent(false);
  try {
    Handler fileHandler = new FileHandler(tomcat.getHost().getAppBase() + "/catalina.out", true);
    fileHandler.setFormatter(new SimpleFormatter());
    fileHandler.setLevel(level);
    java.util.logging.Logger.getLogger("").addHandler(fileHandler);
  } catch (IOException e) {
    throw new RuntimeException("Unable to configure embedded tomcat logging.");
  }
}
 
Example 7
Source File: PythonProject.java    From AndroidRobot with Apache License 2.0 5 votes vote down vote up
private static final void replaceAllLogFormatters(Formatter form, Level level)
/*     */   {
/* 179 */     LogManager mgr = LogManager.getLogManager();
/* 180 */     Enumeration loggerNames = mgr.getLoggerNames();
/* 181 */     while (loggerNames.hasMoreElements()) {
/* 182 */       String loggerName = (String)loggerNames.nextElement();
/* 183 */       Logger logger = mgr.getLogger(loggerName);
/* 184 */       for (Handler handler : logger.getHandlers()) {
/* 185 */         handler.setFormatter(form);
/* 186 */         handler.setLevel(level);
/*     */       }
/*     */     }
/*     */   }
 
Example 8
Source File: DConnectServerNanoHttpd.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
/**
 * 設定値を元にサーバーを構築します.
 *
 * SSL設定がONの場合は、SSLServerSocketFactoryを指定する必要があります.
 *
 * @param config  サーバー設定。
 * @param context コンテキストオブジェクト。
 * @param socketFactory SSLサーバーソケットファクトリー
 * @throws IllegalArgumentException SSL設定がONのときに socketFactory に<coce>null</coce>を指定した場合
 */
public DConnectServerNanoHttpd(final DConnectServerConfig config, final Context context,
                               final SSLServerSocketFactory socketFactory) {
    super(config);

    if (context == null) {
        throw new IllegalArgumentException("context must not be null.");
    }
    mContext = context;

    if (config.isSsl() && socketFactory == null) {
        throw new IllegalArgumentException("keyStoreManager must not be null if SSL is enabled.");
    }
    mServerSocketFactory = socketFactory;
    mAccessLogProvider = new AccessLogProvider(context);

    if (BuildConfig.DEBUG) {
        Handler handler = new AndroidHandler(TAG);
        handler.setFormatter(new SimpleFormatter());
        handler.setLevel(Level.ALL);
        mLogger.addHandler(handler);
        mLogger.setLevel(Level.WARNING);
        mLogger.setUseParentHandlers(false);
    } else {
        mLogger.setLevel(Level.OFF);
    }
}
 
Example 9
Source File: Firewall.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
/**
 * 接続元のIP制限リストを指定してファイアウォールを生成する.
 * 
 * @param ipList IPのホワイトリスト。
 */
public Firewall(final List<String> ipList) {
    mIPWhiteList = ipList;
    if (BuildConfig.DEBUG) {
        Handler handler = new AndroidHandler(TAG);
        handler.setFormatter(new SimpleFormatter());
        handler.setLevel(Level.ALL);
        mLogger.addHandler(handler);
        mLogger.setLevel(Level.WARNING);
    }
}
 
Example 10
Source File: ProxyModule.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/**
 * Configure logging parameters depending on the {@link Environment}.
 *
 * <p>If not running locally, set the logging formatter to {@link GcpJsonFormatter} that formats
 * the log in a single-line json string printed to {@code STDOUT} or {@code STDERR}, will be
 * correctly parsed by Stackdriver logging.
 *
 * @see <a href="https://cloud.google.com/kubernetes-engine/docs/how-to/logging#best_practices">
 *     Logging Best Practices</a>
 */
private void configureLogging() {
  // Remove all other handlers on the root logger to avoid double logging.
  LoggerConfig rootLoggerConfig = LoggerConfig.getConfig("");
  Arrays.asList(rootLoggerConfig.getHandlers()).forEach(rootLoggerConfig::removeHandler);

  // If running on in a non-local environment, use GCP JSON formatter.
  Handler rootHandler = new ConsoleHandler();
  rootHandler.setLevel(Level.FINE);
  if (env != Environment.LOCAL) {
    rootHandler.setFormatter(new GcpJsonFormatter());
  }
  rootLoggerConfig.addHandler(rootHandler);

  if (log) {
    // The LoggingHandler records logs at LogLevel.DEBUG (internal Netty log level), which
    // corresponds to Level.FINE (JUL log level). It uses a JUL logger with the name
    // "io.netty.handler.logging.LoggingHandler" to actually process the logs. This JUL logger is
    // set to Level.FINE if the --log parameter is passed, so that it does not filter out logs
    // that the LoggingHandler writes. Otherwise the logs are silently ignored because the default
    // JUL logger level is Level.INFO.
    LoggerConfig.getConfig(LoggingHandler.class).setLevel(Level.FINE);
    // Log source IP information if --log parameter is passed. This is considered PII and should
    // only be used in non-production environment for debugging purpose.
    LoggerConfig.getConfig(ProxyProtocolHandler.class).setLevel(Level.FINE);
  }
}
 
Example 11
Source File: Logging.java    From openjdk-8 with 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);
    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 logger;
}
 
Example 12
Source File: Logging.java    From nashorn with 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);
    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 logger;
}
 
Example 13
Source File: NadiaProcessor.java    From nadia with 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 14
Source File: TestCanvas.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void main(String[] args){
    JmeFormatter formatter = new JmeFormatter();

    Handler consoleHandler = new ConsoleHandler();
    consoleHandler.setFormatter(formatter);

    Logger.getLogger("").removeHandler(Logger.getLogger("").getHandlers()[0]);
    Logger.getLogger("").addHandler(consoleHandler);
    
    createCanvas(appClass);
    
    try {
        Thread.sleep(500);
    } catch (InterruptedException ex) {
    }
    
    SwingUtilities.invokeLater(new Runnable(){
        public void run(){
            JPopupMenu.setDefaultLightWeightPopupEnabled(false);

            createFrame();
            
            currentPanel.add(canvas, BorderLayout.CENTER);
            frame.pack();
            startApp();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    });
}
 
Example 15
Source File: LoggingManager.java    From selenium with 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 16
Source File: Log.java    From EnchantmentCracker with MIT License 5 votes vote down vote up
private static Logger getLogger() {
	Logger logger = Logger.getLogger("");
	logger.setUseParentHandlers(false);
	logger.addHandler(fileHandler);
	SimpleFormatter formatter = new SimpleFormatter() {
		private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		@Override
		public String format(LogRecord record) {
			String thrown;
			if (record.getThrown() == null) {
				thrown = "";
			} else {
				StringWriter sw = new StringWriter();
				PrintWriter pw = new PrintWriter(sw);
				pw.println();
				record.getThrown().printStackTrace(pw);
				thrown = sw.toString();
			}
			return String.format("[%s] [%s/%s]: %s%s%n", dateFormat.format(record.getMillis()),
					record.getLoggerName(), record.getLevel(), record.getMessage(), thrown);
		}
	};
	for (Handler handler : logger.getHandlers()) {
		handler.setFormatter(formatter);
	}

	return logger;
}
 
Example 17
Source File: LoggerUtil.java    From sagacity-sqltoy with Apache License 2.0 5 votes vote down vote up
public static Logger getLogger() {
	if (logger == null) {
		logger = Logger.getLogger("sagacity.quickvo");
		logger.setLevel(Level.ALL);
		try {
			Handler handler = new FileHandler(FileUtil.linkPath(QuickVOConstants.BASE_LOCATE, "quickvo.log"));
			handler.setFormatter(new SimpleFormatter());
			logger.addHandler(handler);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	return logger;
}
 
Example 18
Source File: UicdCLI.java    From android-uiconductor with Apache License 2.0 5 votes vote down vote up
private static void setRedirectOutputToFile(Path logFolder) throws IOException {
  Path logFilePath =
      Paths.get(logFolder.toString(), LOG_FILENAME_PREFIX + new Date().getTime() + ".txt");
  System.out.println("Starting print to file...\n" + logFilePath.toString());
  Handler fh = new FileHandler(logFilePath.toString());
  fh.setFormatter(new SimpleFormatter());

  // Remove the output in the console.
  LogManager.getLogManager().reset();
  Logger.getLogger("uicd").addHandler(fh);
}
 
Example 19
Source File: Log.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private Logger getPackageLogger() {
      if (logger == null) {
          String prop = System.getProperty(packageName, DEFAULT_NAME);
          for (int i = 1; i < LEVELS.length; i++) {
              if (prop.toLowerCase().equals(LEVEL_NAMES[i].toLowerCase())) {
                  level = LEVELS[i];
                  break;
              }
          }
          LogManager.getLogManager().addLogger(new Logger(packageName, null)
{});
          logger = LogManager.getLogManager().getLogger(packageName);
          if (logger == null) {
              System.out.println(packageName + ": "
		   + rb.getString("CANT_GET_LOGGER"));
              return Logger.getLogger("global");
          }
          try {
              logger.setLevel(level);
              Handler handler = new ConsoleHandler();
              handler.setLevel(level);
// Default handlers don't provide class name or method name, so roll our own
logger.setUseParentHandlers(false);
Formatter formatter = new Formatter() {
	public String format(LogRecord record) {
	    StringBuffer s = new StringBuffer();
	    s.append(record.getLevel().getLocalizedName());
	    s.append(' ');
	    if (record.getLoggerName() != null) {
		s.append('[');
		s.append(record.getLoggerName());
		s.append("]: ");
	    }
	    if (record.getSourceClassName() != null) {
		s.append("| ");
		if (record.getLevel().equals(Level.FINEST)) {
		    String className = record.getSourceClassName();
		    s.append(className.substring(Math.max(className.lastIndexOf('.')+1,0)));
		} else {
		    s.append(record.getSourceClassName());
		}
		s.append(' ');
	    }
	    if (record.getSourceMethodName() != null) {
		s.append("|  ");
		s.append(record.getSourceMethodName());
		s.append("( ");
		Object[] parms = record.getParameters();
		if (parms != null) {
		    for (int i = 0; i < parms.length; i++) {
			if (i != 0) {
			    s.append(", ");
			}
			s.append(parms[i]);
		    }
		}
		s.append(" ) ");
	    }
	    if (record.getThrown() != null) {
		s.append("| ");
		s.append(record.getThrown());
	    }
	    if (record.getMessage() != null) {
		s.append('|');
		s.append(record.getMessage());
	    }
	    s.append('\n');
	    return s.toString();
	}
                  };
              handler.setFormatter(formatter);
              logger.addHandler(handler);
          }
          catch (SecurityException e) {
          }
      }

      return logger;
  }
 
Example 20
Source File: BriefLogFormatter.java    From RipplePower with Apache License 2.0 4 votes vote down vote up
public static void init() {
	Handler[] handlers = logger.getHandlers();
	for (Handler handler : handlers) {
		handler.setFormatter(new BriefLogFormatter());
	}
}