Domanda

I understand that I can use

Logger.setLevel(<level here>);

To set the level of logging (turn it off, turn it on, etc). However, I'm not sure how I can conditionally log based on the log level the user specifies.

In essence, I have a class that uses the logging API. I wish to give the user of the class the power to configure the log level how they please. I've seen this done with log4j but not with the logging API.

Is there a best practice for this? Should I just have some function

setLogLevel()

that the user can pass a Level.INFO or whatever to? Or is there a better way?

Thank you!

È stato utile?

Soluzione

I'm not sure, if understand this question correctly, but you shouldn't set the logging level from the code, which calls the logger. The idea behind logging is, that the developer logs all messages at the appropriate level. For example "Started to compute xyz" at DEBUG level, "New user have been set into DB" at INFO level and "Caught exception from..." at ERROR level. The logger will print the message only if it has the same or higher logging level. The logging level should be set according to environment, for example DEBUG for development and INFO for production, from outside the application.

Conditional logging is useful if the creation of the message is time consuming and you don't want to create the log message unless it will be really logged (check out this link). If you want to check, that the logger from the java.util.logging will actually log at given level, you can use this method.

Altri suggerimenti

However, I'm not sure how I can conditionally log based on the log level the user specifies.

Your question is unclear, but I think you are asking how log stuff depending on the log level that the user sets. The answer to that is that you just write your log statements normally; e.g.

logger.warning("Danger Will Robinson");
...
anotherLogger.info("It's good to be alive");

... and let the user specify what logging to capture using the logging configuration. Generally speaking the logging configuration is specified by a config file that is loaded at runtime, and can be altered by the user. It is also possible to create or alter the logging configuration programmatically, though presenting this functionality to the user via some kind of user-friendly UI is going to be something of a challenge.

In theory, it is also possible to a given log events at different levels depending on some condition. However, you are probably taking control away from the user by doing that.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top