下面列出了java.util.logging.Level#parse ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
protected void configureLogger() throws SecurityException, IOException {
if (logger == null) {
logger = Logger.getLogger(LOGGER_NAME);
}
logger.setUseParentHandlers(false);
logFileHandler = new FileHandler(logFilePath);
logFileHandler.setFormatter(new SimpleFormatter());
Level logLevel = Level.INFO;
try {
logLevel = Level.parse(logLevelString);
} catch (IllegalArgumentException e) {
logInfo("Unrecognized log level :" + logLevelString + " defaulting to :" + logLevel);
}
logFileHandler.setLevel(logLevel);
logger.addHandler(logFileHandler);
}
/**
* Try to parse a log level from the given value. If the given value
* cannot be parsed, then a warning will be printed and <code>INFO</code>
* will be returned.
*
* @param value The value
* @return The log level
*/
private static Level parseLogLevel(String value)
{
if (value == null)
{
logger.warning("Invalid log level: "+value);
return Level.INFO;
}
try
{
return Level.parse(value);
}
catch (IllegalArgumentException e)
{
logger.warning("Invalid log level: "+value);
return Level.INFO;
}
}
/**
* Register our presence and look up any required parameters for this class.
* @see Config#registerSelf(Class)
*/
public static void registerConfig() {
// Register ourselves.
Config.registerSelf( Log.class );
// Now we can use the Log parameters
if (loggerHandler != null) {
loggerHandler.setFormatter(logFormatter = new LogThreadFormatter());
logFormatter.setSquashExceptions(!Config.parms.getBoolean("st"));
try {
loggerLevel = Level.parse(Config.parms.getString("vo"));
logger.setLevel(loggerLevel);
loggerHandler.setLevel(loggerLevel);
} catch (IllegalArgumentException e) {
Config.logger
.log(Level.WARNING, "-vo is out of valid range", e);
}
} // end if loggerHandler!=null
}
/**
* Set logging levels from shared preferences
*/
private void setLogLevels()
{
// get level from preferences
Level level;
try
{
level = Level.parse(prefs.getString(LOG_MASTER, "INFO"));
}
catch(Exception e)
{
level = Level.INFO;
}
// set logger main level
MainActivity.rootLogger.setLevel(level);
}
private Level getLevelValue(String propertyName) {
Level retVal = null;
String stringValue = System.getProperty(propertyName);
if (stringValue != null) {
// if value is not null => property is set, we will try to override the default logging level
LOGGER.fine(TubelineassemblyMessages.MASM_0018_MSG_LOGGING_SYSTEM_PROPERTY_SET_TO_VALUE(propertyName, stringValue));
try {
retVal = Level.parse(stringValue);
} catch (IllegalArgumentException ex) {
LOGGER.warning(TubelineassemblyMessages.MASM_0019_MSG_LOGGING_SYSTEM_PROPERTY_ILLEGAL_VALUE(propertyName, stringValue), ex);
}
}
return retVal;
}
@SuppressWarnings("unchecked")
public static ApplicationConfigOptions generateFromConfig(Map<String, Object> yamlOptions) {
ApplicationConfigOptions options = new ApplicationConfigOptions();
if (yamlOptions.get("domain") != null)
options.domain = (String) yamlOptions.get("domain");
if (yamlOptions.get("logLevel") != null) {
final String logLevelName = (String) yamlOptions.get("logLevel");
options.logLevel = Level.parse(logLevelName);
}
if (yamlOptions.get("mqtt") instanceof Map<?, ?>) {
options.mqtt = ApplicationConfigOptionsMqtt
.generateFromConfig((Map<String, Object>) yamlOptions.get("mqtt"));
}
// else mqtt is missing or in the wrong format
return options;
}
/**
* Initialization function that is called to instantiate the logging system. It takes
* logger names (keys) and logging labels respectively
*
* @param map a map where the key is a logger name and the value a logging level
* @throws IllegalArgumentException if level or names cannot be parsed
*/
private void initialize(final Map<String, String> logMap) throws IllegalArgumentException {
try {
for (final Entry<String, String> entry : logMap.entrySet()) {
Level level;
final String name = lastPart(entry.getKey());
final String levelString = entry.getValue().toUpperCase(Locale.ENGLISH);
final boolean isQuiet;
if ("".equals(levelString)) {
level = Level.INFO;
isQuiet = false;
} else if ("QUIET".equals(levelString)) {
level = Level.INFO;
isQuiet = true;
} else {
level = Level.parse(levelString);
isQuiet = false;
}
loggers.put(name, new LoggerInfo(level, isQuiet));
}
} catch (final IllegalArgumentException | SecurityException e) {
throw e;
}
}
/**
* Initialization function that is called to instantiate the logging system. It takes
* logger names (keys) and logging labels respectively
*
* @param map a map where the key is a logger name and the value a logging level
* @throws IllegalArgumentException if level or names cannot be parsed
*/
private void initialize(final Map<String, String> logMap) throws IllegalArgumentException {
try {
for (final Entry<String, String> entry : logMap.entrySet()) {
Level level;
final String name = lastPart(entry.getKey());
final String levelString = entry.getValue().toUpperCase(Locale.ENGLISH);
final boolean isQuiet;
if ("".equals(levelString)) {
level = Level.INFO;
isQuiet = false;
} else if ("QUIET".equals(levelString)) {
level = Level.INFO;
isQuiet = true;
} else {
level = Level.parse(levelString);
isQuiet = false;
}
loggers.put(name, new LoggerInfo(level, isQuiet));
}
} catch (final IllegalArgumentException | SecurityException e) {
throw e;
}
}
@FeatureConstructor({"enabled", "messageLoggingRoot", "messageLoggingLevel", "storeMessages"})
public MessageDumpingFeature(boolean enabled, String msgLogRoot, String msgLogLevel, boolean storeMessages) {
// this constructor is here just to satisfy JAX-WS specification requirements
this(msgLogRoot, Level.parse(msgLogLevel), storeMessages);
super.enabled = enabled;
}
/**
* Simplification: use delegate to {@link Level#parse(String)} even if the behavior is slightly different for localized log levels.
*
* @param name {@code null} or empty returns {@code null}
* @return
*/
@Nullable
public static Level findLevel(@Nullable String name) {
if(name == null || name.isEmpty())
return null;
return Level.parse(name);
}
public static DeviceConfigOptions generateFromEnv() {
DeviceConfigOptions options = new DeviceConfigOptions();
if (System.getenv("WIOTP_OPTIONS_DOMAIN") != null)
options.domain = System.getenv("WIOTP_OPTIONS_DOMAIN");
if (System.getenv("WIOTP_OPTIONS_LOGLEVEL") != null) {
final String logLevelName = System.getenv("WIOTP_OPTIONS_LOGLEVEL");
options.logLevel = Level.parse(logLevelName);
}
options.mqtt = DeviceConfigOptionsMqtt.generateFromEnv();
return options;
}
/**
* Create new rule.
*
* @param inequalitySymbol inequality symbol.
* @param value Symbolic name of comparison level.
* @return instance of AbstractRule.
*/
public static Rule getRule(final String inequalitySymbol, final String value) {
Level thisLevel;
// if valid util.logging levels are used against events
// with log4j levels, the
// DEBUG level is used and an illegalargumentexception won't be generated
// an illegalargumentexception is only generated
// if the user types a level name
// that doesn't exist as either a log4j or util.logging level name
if (levelList.contains(value.toUpperCase())) {
thisLevel = Level.parse(value.toUpperCase());
} else {
throw new IllegalArgumentException("Invalid level inequality rule - " + value + " is not a supported level");
}
if ("<".equals(inequalitySymbol)) {
return new LessThanRule(thisLevel);
}
if (">".equals(inequalitySymbol)) {
return new GreaterThanRule(thisLevel);
}
if ("<=".equals(inequalitySymbol)) {
return new LessThanEqualsRule(thisLevel);
}
if (">=".equals(inequalitySymbol)) {
return new GreaterThanEqualsRule(thisLevel);
}
return null;
}
protected void setLoggingLevels() throws Exception
{
LogConfigs logConfigs = getTestClass().getAnnotation(LogConfigs.class);
LogConfig[] logs = null;
if (logConfigs != null)
logs = logConfigs.value();
if (logs == null) {
List<LogConfig> temp = new ArrayList<>();
Annotation[] annotations = getTestClass().getAnnotations();
for (Annotation annotation : annotations) {
if (annotation instanceof LogConfig) {
temp.add((LogConfig) annotation);
}
}
logs = temp.toArray(new LogConfig[temp.size()]);
}
for (LogConfig config : logs) {
Logger log = Logger.getLogger(config.value());
_loggers.add(log); //GC protect
Level level = Level.parse(config.level());
log.setLevel(level);
Handler handler = getHandler(config);
if (handler == null)
continue;
if (handler.getLevel().intValue() > level.intValue())
handler.setLevel(level);
log.addHandler(handler);
}
}
public static Level getDefaultLogLevel() {
final String logLevelProperty = System.getProperty("selenium.LOGGER.level");
if (null == logLevelProperty) {
return null;
}
return Level.parse(logLevelProperty);
}
public LogMetricsPublisher(MetricsConfig metricsConfig) {
super(metricsConfig.getClusterId());
if (!metricsConfig.getLogMetricsConfig().getLogLevel().isEmpty()) {
logLevel = Level.parse(metricsConfig.getLogMetricsConfig().getLogLevel());
} else {
logLevel = Level.FINEST;
}
}
/**
* Configure the given loggers to send their output to the given folder.
* @param loggers map of logger names as key and log level as value
* (strings)
* @param defaultLevel default level to be used if the given value is empty
* or "DEFAULT"
* @param directoryName name of the directory to put the output file
* @see #generateUniqueLogFileName(String, String)
*/
public static void configureLoggers(
Map loggers,
Level defaultLevel,
String directoryName )
{
// configure loggers to enable logging in the given directory
for (
Iterator i = loggers.entrySet( ).iterator( );
i.hasNext();
)
{
Map.Entry entry = (Map.Entry)i.next( );
String loggerName = (String) entry.getKey( );
String levelName =
(String) entry.getValue( );
// set default level
Level level = defaultLevel;
if ( levelName != null
&& !"".equals(levelName) //$NON-NLS-1$
)
{
try
{
levelName = levelName.trim();
if ( !"DEFAULT".equals( levelName ) ) //$NON-NLS-1$
{
level = Level.parse( levelName.trim( ) );
}
}
catch ( IllegalArgumentException e )
{
logger.log( Level.WARNING, e.getMessage( ), e );
}
}
initFileLogger(
loggerName,
level,
directoryName
);
}
}
public void setLogLevel(String logLevel) {
this.logLevel = Level.parse(logLevel);
}
static Level parseLevel(String lev) {
return "USER".equals(lev) ? Level.SEVERE : Level.parse(lev);
}
public List<Stage.ConfigIssue> init(List<Stage.ConfigIssue> issues, Stage.Context context) {
this.context = context;
if (jerseyClientConfig.tlsConfig.isEnabled()) {
jerseyClientConfig.tlsConfig.init(
context,
Groups.TLS.name(),
SSL_CONFIG_PREFIX,
issues
);
}
resourceVars = context.createELVars();
resourceEval = context.createELEval(RESOURCE_CONFIG_NAME);
methodVars = context.createELVars();
methodEval = context.createELEval(HTTP_METHOD_CONFIG_NAME);
headerVars = context.createELVars();
headerEval = context.createELEval(HEADER_CONFIG_NAME);
String proxyUsername = null;
String proxyPassword = null;
if(jerseyClientConfig.useProxy) {
proxyUsername = jerseyClientConfig.proxy.resolveUsername(context, Groups.PROXY.name(), "conf.client.proxy.", issues);
proxyPassword = jerseyClientConfig.proxy.resolvePassword(context, Groups.PROXY.name(), "conf.client.proxy.", issues);
}
jerseyClientConfig.init(context, Groups.PROXY.name(), "conf.client.", issues);
// Validation succeeded so configure the client.
if (issues.isEmpty()) {
ClientConfig clientConfig = new ClientConfig()
.property(ClientProperties.CONNECT_TIMEOUT, jerseyClientConfig.connectTimeoutMillis)
.property(ClientProperties.READ_TIMEOUT, jerseyClientConfig.readTimeoutMillis)
.property(ClientProperties.ASYNC_THREADPOOL_SIZE, jerseyClientConfig.numThreads);
if(jerseyClientConfig.useProxy) {
clientConfig = clientConfig.connectorProvider(new GrizzlyConnectorProvider(new GrizzlyClientCustomizer(
jerseyClientConfig.useProxy,
proxyUsername,
proxyPassword
)));
}
clientBuilder = ClientBuilder.newBuilder().withConfig(clientConfig);
if (jerseyClientConfig.requestLoggingConfig.enableRequestLogging) {
Feature feature = new LoggingFeature(
REQUEST_LOGGER,
Level.parse(jerseyClientConfig.requestLoggingConfig.logLevel),
jerseyClientConfig.requestLoggingConfig.verbosity, jerseyClientConfig.requestLoggingConfig.maxEntitySize
);
clientBuilder = clientBuilder.register(feature);
}
configureCompression(clientBuilder);
if (jerseyClientConfig.useProxy) {
JerseyClientUtil.configureProxy(
jerseyClientConfig.proxy.uri,
proxyUsername,
proxyPassword, clientBuilder
);
}
JerseyClientUtil.configureSslContext(jerseyClientConfig.tlsConfig, clientBuilder);
configureAuthAndBuildClient(clientBuilder, issues);
}
return issues;
}
private void parseArguments(String[] args) throws Exception {
Builder b = JCommander.newBuilder();
b.addObject(this);
JCommander jc = b.build();
jc.setProgramName("Experiments.java"); //todo maybe add copyright etcetc
try {
jc.parse(args);
} catch (Exception e) {
if (!help) {
//we actually errored, instead of the program simply being called with the --help flag
System.err.println("Parsing of arguments failed, parameter information follows after the error. Parameters that require values should have the flag and value separated by '='.");
System.err.println("For example: java -jar TimeSeriesClassification.jar -dp=data/path/ -rp=results/path/ -cn=someClassifier -dn=someDataset -f=0");
System.err.println("Parameters prefixed by a * are REQUIRED. These are the first five parameters, which are needed to run a basic experiment.");
System.err.println("Error: \n\t"+e+"\n\n");
}
jc.usage();
// Thread.sleep(1000); //usage can take a second to print for some reason?... no idea what it's actually doing
// System.exit(1);
}
foldId -= 1; //go from one-indexed to zero-indexed
Experiments.debug = this.debug;
resultsWriteLocation = StrUtils.asDirPath(resultsWriteLocation);
dataReadLocation = StrUtils.asDirPath(dataReadLocation);
if (checkpointingStr != null) {
//some kind of checkpointing is wanted
// is it simply "true"?
checkpointing = Boolean.parseBoolean(checkpointingStr.toLowerCase());
if(!checkpointing){
//it's not. must be a timing string
checkpointing = true;
checkpointInterval = parseTiming(checkpointingStr);
}
}
//populating the contract times if present
if (contractTrainTimeString != null)
contractTrainTimeNanos = parseTiming(contractTrainTimeString);
if (contractTestTimeString != null)
contractTestTimeNanos = parseTiming(contractTestTimeString);
if(contractTrainTimeNanos > 0) {
trainContracts.add(String.valueOf(contractTrainTimeNanos));
trainContracts.add(TimeUnit.NANOSECONDS.toString());
}
// check the contracts are in ascending order // todo sort them
for(int i = 1; i < trainContracts.size(); i += 2) {
trainContracts.set(i, trainContracts.get(i).toUpperCase());
}
long prev = -1;
for(int i = 0; i < trainContracts.size(); i += 2) {
long nanos = TimeUnit.NANOSECONDS.convert(Long.parseLong(trainContracts.get(i)),
TimeUnit.valueOf(trainContracts.get(i + 1)));
if(prev > nanos) {
throw new IllegalArgumentException("contracts not in asc order");
}
prev = nanos;
}
if(trainContracts.size() % 2 != 0) {
throw new IllegalStateException("illegal number of args for time");
}
if(logLevelStr != null) {
logLevel = Level.parse(logLevelStr);
}
}