001package ca.uhn.fhir.test.utilities; 002 003/*- 004 * #%L 005 * HAPI FHIR Test Utilities 006 * %% 007 * Copyright (C) 2014 - 2023 Smile CDR, Inc. 008 * %% 009 * Licensed under the Apache License, Version 2.0 (the "License"); 010 * you may not use this file except in compliance with the License. 011 * You may obtain a copy of the License at 012 * 013 * http://www.apache.org/licenses/LICENSE-2.0 014 * 015 * Unless required by applicable law or agreed to in writing, software 016 * distributed under the License is distributed on an "AS IS" BASIS, 017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 018 * See the License for the specific language governing permissions and 019 * limitations under the License. 020 * #L% 021 */ 022 023import ch.qos.logback.classic.Level; 024import ch.qos.logback.classic.Logger; 025import org.junit.jupiter.api.extension.AfterEachCallback; 026import org.junit.jupiter.api.extension.ExtensionContext; 027import org.slf4j.LoggerFactory; 028 029import java.util.HashMap; 030import java.util.Map; 031 032/** 033 * Extension to allow temporary log elevation for a single test. 034 * 035 */ 036public class LogbackLevelOverrideExtension implements AfterEachCallback { 037 038 private final Map<String, Level> mySavedLevels = new HashMap<>(); 039 040 public void setLogLevel(Class theClass, Level theLevel) { 041 String name = theClass.getName(); 042 Logger logger = getClassicLogger(name); 043 if (!mySavedLevels.containsKey(name)) { 044 // level can be null 045 mySavedLevels.put(name, logger.getLevel()); 046 } 047 logger.setLevel(theLevel); 048 } 049 050 private Logger getClassicLogger(String name) { 051 return (Logger) LoggerFactory.getLogger(name); 052 } 053 054 @Override 055 public void afterEach(ExtensionContext context) throws Exception { 056 mySavedLevels.forEach((name,level) ->{ 057 getClassicLogger(name).setLevel(level); 058 }); 059 mySavedLevels.clear(); 060 } 061 062 public void resetLevel(Class theClass) { 063 String name = theClass.getName(); 064 if (mySavedLevels.containsKey(name)) { 065 getClassicLogger(name).setLevel(mySavedLevels.get(name)); 066 mySavedLevels.remove(name); 067 } 068 } 069}