LoggerController.java

/*
 * Copyright 2020 Global Crop Diversity Trust
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gringlobal.mvc.admin;

import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/admin/logger")
@PreAuthorize("hasAuthority('GROUP_ADMINS')")
public class LoggerController {

	@RequestMapping(method = RequestMethod.GET, value = "/")
	public String adjustLogger(Model model) {
		model.addAttribute("loggers", getAllLoggers());
		return "/admin/logger/index";
	}

	@RequestMapping(method = RequestMethod.GET, value = "/{loggerName}")
	public String adjustLoggerPage(Model model, @PathVariable(value = "loggerName") String loggerName) {
		LoggerContext context = (LoggerContext) LogManager.getContext(false);
		Logger logger;

		if ("root".equalsIgnoreCase(loggerName))
			logger = context.getRootLogger();
		else
			logger = context.getLogger(loggerName);

		model.addAttribute("logger", logger);
		model.addAttribute("appenders", context.getConfiguration().getAppenders().values());
		return "/admin/logger/edit";
	}

	@RequestMapping(method = RequestMethod.POST, value = "/changeLoger")
	public String changeLogger(@RequestParam(value = "loggerLevel") String loggerLevel, @RequestParam(value = "loggerName") String loggerName) {
		LoggerContext context = (LoggerContext) LogManager.getContext(false);
		Configuration config = context.getConfiguration();

		LoggerConfig loggerConfig;

		if (loggerName == null || "root".equalsIgnoreCase(loggerName)) {
			loggerConfig = config.getRootLogger();
		} else {
			loggerConfig = config.getLoggerConfig(loggerName);
		}

		if (loggerConfig != null) {
			loggerConfig.setLevel(loggerLevel == null ? null : Level.toLevel(loggerLevel));
			context.updateLoggers();
		}

		return "redirect:/admin/logger/";
	}

	private List<Logger> getAllLoggers() {
		List<Logger> loggers = new ArrayList<>();

		LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false);
		Configuration config = loggerContext.getConfiguration();

		config.getLoggers().keySet().forEach(loggerName -> loggers.add(loggerContext.getLogger(loggerName)));

		loggers.sort((o1, o2) -> {
			// root logger is on the top
			if (loggerContext.getRootLogger() == o1) {
				return -1;
			}
			if (loggerContext.getRootLogger() == o2) {
				return 1;
			}
			// otherwise sort by name
			return o1.getName().compareTo(o2.getName());
		});

		return loggers;
	}

	@RequestMapping(method = RequestMethod.POST, value = "/addLoger")
	public String addLogger(@RequestParam(value = "nameNewLogger") String nameNewLogger, @RequestParam("loggerLevel") String loggerLevel) {
		LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false);
		Configuration config = loggerContext.getConfiguration();
		Level level = Level.toLevel(loggerLevel);

		LoggerConfig loggerConfig = new LoggerConfig(nameNewLogger, level, false);
		Appender appender = config.getRootLogger().getAppenders().values().stream().findFirst().orElse(null);
		loggerConfig.addAppender(appender, level, null);
		config.addLogger(nameNewLogger, loggerConfig);

		loggerContext.updateLoggers();

		return "redirect:/admin/logger/";
	}
}