John Mercier
John Mercier

Reputation: 1705

How to set root log level for application in micronaut

I am working on a cli application that can take in some options: --info, --debug, --trace. I would like to use the arguments to set the logging level for the entire application. Is there an easy way to do this? This is what I have tried so far:

    LogLevel level;
    if(info) {
      level = LogLevel.INFO;
    } else if (debug) {
      level = LogLevel.DEBUG;
    } else if (trace) {
      level = LogLevel.TRACE;
    } else {
      level = LogLevel.WARN;
    }
    loggingSystem.setLogLevel(Logger.ROOT_LOGGER_NAME, level);

loggingSystem is injected into the class.

  @Inject
  private LoggingSystem loggingSystem;

Upvotes: 1

Views: 17171

Answers (3)

Piotr
Piotr

Reputation: 72

From what I understand you are asking just to find a more handy way of doing so, because your example (from question) is working.

You can try something like

    @Inject
    LoggingSystem loggingSystem;

    @Option(names = {"-l", "--log"}, defaultValue = "INFO", description = "Log level, available: TRACE, DEBUG, INFO, WARN, ERROR")
    String logLevel;


    public void run() {
       loggingSystem.setLogLevel(Logger.ROOT_LOGGER_NAME,  LogLevel.valueOf(logLevel));

    }

Upvotes: 0

Armando Prieto
Armando Prieto

Reputation: 129

Create a method to do the work:

 public String setLogLevel(String loggerName, Level level) {
    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
    Logger logger = loggerName.equalsIgnoreCase("root") ?
            loggerContext.getLogger(loggerName) : loggerContext.exists(loggerName);
    if (logger != null) {
        logger.setLevel(level);
        return loggerName + " to level : " + level;
    } else {
        return "Logger Not Found";
    }
}

Upvotes: 0

Mafick
Mafick

Reputation: 1170

I am not quite sure if I get your point. Here is what I found in the official documentation.

Controlling Log Levels with Properties

Controlling Log Levels with Properties

Log levels can be configured via properties defined in application.yml (and environment variables) with the log.level prefix:

logger:
    levels:
        foo.bar: ERROR

Note that the ability to control log levels via config is controlled via the LoggingSystem interface. Currently Micronaut ships with a single implementation that allows setting log levels for the Logback library. If another library is chosen you should provide a bean that implements this interface.

Upvotes: 8

Related Questions