001/* 002 * Copyright 2018-2018 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.boot.devtools.logger; 018 019import java.util.LinkedHashMap; 020import java.util.Map; 021 022import org.apache.commons.logging.Log; 023 024import org.springframework.boot.context.event.ApplicationPreparedEvent; 025import org.springframework.boot.logging.DeferredLog; 026import org.springframework.context.ApplicationListener; 027 028/** 029 * Devtools deferred logging support. 030 * 031 * @author Phillip Webb 032 * @since 2.1.0 033 */ 034public final class DevToolsLogFactory { 035 036 private static final Map<Log, Class<?>> logs = new LinkedHashMap<>(); 037 038 private DevToolsLogFactory() { 039 } 040 041 /** 042 * Get a {@link Log} instance for the specified source that will be automatically 043 * {@link DeferredLog#switchTo(Class) switched} when the 044 * {@link ApplicationPreparedEvent context is prepared}. 045 * @param source the source for logging 046 * @return a {@link DeferredLog} instance 047 */ 048 public static Log getLog(Class<?> source) { 049 synchronized (logs) { 050 Log log = new DeferredLog(); 051 logs.put(log, source); 052 return log; 053 } 054 } 055 056 /** 057 * Listener used to log and switch when the context is ready. 058 */ 059 static class Listener implements ApplicationListener<ApplicationPreparedEvent> { 060 061 @Override 062 public void onApplicationEvent(ApplicationPreparedEvent event) { 063 synchronized (logs) { 064 logs.forEach((log, source) -> { 065 if (log instanceof DeferredLog) { 066 ((DeferredLog) log).switchTo(source); 067 } 068 }); 069 logs.clear(); 070 } 071 } 072 073 } 074 075}