3

Quick question,

Looking through these examples which statically assign the logging level of a program

http://www.onjava.com/pub/a/onjava/2002/06/19/log.html?page=2

http://www.vogella.com/articles/Logging/article.html

How can I dynamically set the logging level through an argument when I call my Java application

e.g.

java -jar myprogram.jar FINE

Meaning that instead of this code

 logger.setLevel(Level.INFO); 

I could have something like

logger.setLevel(args[0]); 

When researching the documentation there doesnt appear to be away to set the log level with a string.

http://docs.oracle.com/javase/6/docs/api/java/util/logging/Level.html

0

4 Answers 4

3

You can use builtin method Level.parse(String), which parses a level name string into a Level.

The argument string may consist of either a level name or an integer value.

For example:

  • "SEVERE"
  • "INFO"
  • "1000"
Sign up to request clarification or add additional context in comments.

2 Comments

Will need to be careful about user input for this but thank you :)
@serupticious User input validation is mandatory no matter how you implement it. Btw, with this you get new levels created when you use integers which do not map to a known Level. You might be able to use this to your advantage.
1

You could create a Map of String and Level and refer to that:

logger.setLevel(logmap.get(args[0])); 

Comments

1

You can use a map to store the Level mappings:

Map<String, Level> levelmap = new HashMap<String, Level>(); levelmap.put("info", Level.INFO); 

and then use this map to set the log level:

org.apache.log4j.Logger rootLogger = org.apache.log4j.Logger.getRootLogger(); String level = arg[0]; rootLogger.setLevel(levelmap.get(level)); 

1 Comment

It does not look like he is using Log4j.
1

The Level class is the reference:

 public static final Level INFO = new Level("INFO", 800, defaultBundle); 

You could map from a String like "INFO" to some constant like Level.INFO and so on...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.