001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.rest.server.management.logging;
018
019import static org.apache.juneau.commons.utils.Shorts.*;
020
021import java.util.*;
022
023import org.apache.juneau.rest.server.management.*;
024import org.slf4j.*;
025import org.slf4j.Logger;
026
027import ch.qos.logback.classic.*;
028
029/**
030 * {@link LogBackend} adapter for <a class="doclink" href="https://logback.qos.ch">Logback</a> (the SLF4J native
031 * backend), for use behind the {@code /loggers} management endpoint.
032 *
033 * <p>
034 * Drives the concrete Logback {@link LoggerContext} &mdash; <b>not</b> SLF4J the facade. Register it explicitly:
035 *
036 * <p class='bjava'>
037 *    <ja>@Bean</ja>
038 *    <jk>public</jk> LoggersSettings loggersSettings() {
039 *       <jk>return</jk> LoggersSettings.<jsm>create</jsm>().enableWrite().backend(<jk>new</jk> LogbackLogBackend()).build();
040 *    }
041 * </p>
042 *
043 * <h5 class='topic'>Level mapping</h5>
044 *
045 * <p>
046 * Levels are Logback level names ({@code "TRACE"}, {@code "DEBUG"}, {@code "INFO"}, {@code "WARN"},
047 * {@code "ERROR"}, {@code "OFF"}). Reads report each logger's <b>configured</b> level (the level set on the logger
048 * itself, or the empty string when it inherits from an ancestor). Sets are process-lifetime-only
049 * ({@code Logger.setLevel(...)}); the root logger is addressed as {@code "ROOT"}.
050 *
051 * @since 10.0.0
052 */
053public class LogbackLogBackend implements LogBackend {
054
055   private final LoggerContext context;
056
057   /**
058    * Constructor using the SLF4J-bound Logback {@link LoggerContext}.
059    *
060    * @throws IllegalStateException If the bound SLF4J backend is not Logback.
061    */
062   public LogbackLogBackend() {
063      var factory = LoggerFactory.getILoggerFactory();
064      if (! (factory instanceof LoggerContext factory2))  // HTT: SLF4J binds Logback statically on this module's classpath; a seam (injectable ILoggerFactory) would make this testable
065         throw isex("The bound SLF4J backend is not Logback (ILoggerFactory=%s).  /loggers drives the concrete backend, not the SLF4J facade.", factory.getClass().getName());  // HTT: only reachable when the bound SLF4J backend is not Logback; a seam would make this testable
066      this.context = factory2;
067   }
068
069   /**
070    * Constructor with an explicit {@link LoggerContext} (for tests / multi-context setups).
071    *
072    * @param context The Logback logger context. Must not be <jk>null</jk>.
073    */
074   public LogbackLogBackend(LoggerContext context) {
075      this.context = Objects.requireNonNull(context, "context");
076   }
077
078   @Override /* LogBackend */
079   public Map<String,String> getLevels() {
080      var out = new TreeMap<String,String>();
081      for (var logger : context.getLoggerList()) {
082         var level = logger.getLevel();  // configured level; null = inherited
083         var name = logger.getName();
084         var key = Logger.ROOT_LOGGER_NAME.equals(name) ? "ROOT" : name;
085         out.put(key, level == null ? "" : level.toString());
086      }
087      return out;
088   }
089
090   @Override /* LogBackend */
091   public String getLevel(String name) {
092      // Logback exists-check: getLogger(...) creates on demand, so probe the existing list first.
093      var resolved = resolveName(name);
094      for (var logger : context.getLoggerList())
095         if (logger.getName().equals(resolved)) {
096            var level = logger.getLevel();
097            return level == null ? "" : level.toString();
098         }
099      return null;
100   }
101
102   @Override /* LogBackend */
103   public void setLevel(String name, String level) {
104      var logger = context.getLogger(resolveName(name));
105      // A null/blank level clears the logger's own level so it inherits from its ancestor.
106      // Level.toLevel(null) returns DEBUG, so guard the inherit case explicitly.
107      logger.setLevel(level == null || level.isBlank() ? null : parse(level.trim()));
108   }
109
110   private static Level parse(String level) {
111      // Logback's Level.toLevel(name, default) silently falls back; we want a hard failure on a bad name to
112      // match the JUL backend's IllegalArgumentException contract.
113      var l = Level.toLevel(level, null);
114      if (l == null)
115         throw iaex("Not a valid Logback level: '%s'.", level);
116      return l;
117   }
118
119   private static String resolveName(String name) {
120      return (name == null || eq(name, "ROOT")) ? Logger.ROOT_LOGGER_NAME : name;
121   }
122}