LoggerController.java

/*
 * Copyright 2022 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.api.admin.v1;

import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
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.gringlobal.api.v1.ApiBaseController;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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

@RestController("loggerAPIV1")
@RequestMapping(LoggerController.API_URL)
@PreAuthorize("hasAuthority('GROUP_ADMINS')")
@Api(tags = { "loggerv1" })
public class LoggerController {

	/** The Constant API_URL. */
	public static final String API_URL = ApiBaseController.APIv1_BASE + "/admin/logger";

	@GetMapping(value = "", produces = { MediaType.APPLICATION_JSON_VALUE })
	public List<LoggerResponse> getLoggers() {
		return getAllLoggers();
	}

	@GetMapping(value = "/{loggerName}", produces = { MediaType.APPLICATION_JSON_VALUE })
	public LoggerResponse getLogger(@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);

		List<String> appenders = new ArrayList<>(context.getConfiguration().getAppenders().keySet());
		return new LoggerResponse(logger.getName(), logger.getLevel().toString(), appenders);
	}

	@PostMapping(value = "{loggerName}/changeLoger/{loggerLevel}", produces = { MediaType.APPLICATION_JSON_VALUE })
	public LoggerResponse changeLogger(@PathVariable(value = "loggerLevel") String loggerLevel, @PathVariable(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) {
			return null;
		}

		loggerConfig.setLevel(loggerLevel == null ? null : Level.toLevel(loggerLevel));
		context.updateLoggers();
		List<String> appenders = new ArrayList<>(context.getConfiguration().getAppenders().keySet());
		return new LoggerResponse(loggerConfig.getName(), loggerConfig.getLevel().toString(), appenders);
	}

	private List<LoggerResponse> getAllLoggers() {

		List<LoggerResponse> loggers = new ArrayList<>();

		LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false);
		Configuration config = loggerContext.getConfiguration();
		List<String> appenders = new ArrayList<>(loggerContext.getConfiguration().getAppenders().keySet());

		config.getLoggers().values().forEach(loggerConfig -> {
			LoggerResponse loggerResponse = new LoggerResponse();
			loggerResponse.loggerName = loggerConfig.getName();
			loggerResponse.loggerLevel = loggerConfig.getLevel().toString();
			loggerResponse.appenders = appenders;
			loggers.add(loggerResponse);
		});

		loggers.sort((o1, o2) -> {
			// root logger is on the top

			if (StringUtils.isEmpty(o1.loggerName)) {
				return -1;
			} else if (StringUtils.isEmpty(o1.loggerName)) {
				return 1;
			}
			// otherwise sort by name
			return o1.loggerName.compareTo(o2.loggerName);
		});

		return loggers;
	}

	@PostMapping(value = "/addLoger", produces = { MediaType.APPLICATION_JSON_VALUE })
	public LoggerResponse 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();

		List<String> appenders = new ArrayList<>(loggerContext.getConfiguration().getAppenders().keySet());

		return new LoggerResponse(loggerConfig.getName(), loggerConfig.getLevel().toString(), appenders);
	}

	public static class LoggerResponse {
		public String loggerName;
		public String loggerLevel;
		public List<String> appenders;

		public LoggerResponse() {
		}

		public LoggerResponse(String loggerName, String loggerLevel, List<String> appenders) {
			this.loggerName = loggerName;
			this.loggerLevel = loggerLevel;
			this.appenders = appenders;
		}
	}
}