|
| 1 | +/** |
| 2 | + * |
| 3 | + */ |
| 4 | +package com.baeldung.logging.log4j2.appender; |
| 5 | + |
| 6 | +import java.time.Instant; |
| 7 | +import java.util.concurrent.ConcurrentHashMap; |
| 8 | +import java.util.concurrent.ConcurrentMap; |
| 9 | + |
| 10 | +import org.apache.logging.log4j.Level; |
| 11 | +import org.apache.logging.log4j.core.Appender; |
| 12 | +import org.apache.logging.log4j.core.Core; |
| 13 | +import org.apache.logging.log4j.core.Filter; |
| 14 | +import org.apache.logging.log4j.core.LogEvent; |
| 15 | +import org.apache.logging.log4j.core.appender.AbstractAppender; |
| 16 | +import org.apache.logging.log4j.core.config.plugins.Plugin; |
| 17 | +import org.apache.logging.log4j.core.config.plugins.PluginAttribute; |
| 18 | +import org.apache.logging.log4j.core.config.plugins.PluginElement; |
| 19 | +import org.apache.logging.log4j.core.config.plugins.PluginFactory; |
| 20 | + |
| 21 | +@Plugin(name = "MapAppender", category = Core.CATEGORY_NAME, elementType = Appender.ELEMENT_TYPE) |
| 22 | +public class MapAppender extends AbstractAppender { |
| 23 | + |
| 24 | + private ConcurrentMap<String, LogEvent> eventMap = new ConcurrentHashMap<>(); |
| 25 | + |
| 26 | + protected MapAppender(String name, Filter filter) { |
| 27 | + super(name, filter, null); |
| 28 | + } |
| 29 | + |
| 30 | + @PluginFactory |
| 31 | + public static MapAppender createAppender(@PluginAttribute("name") String name, @PluginElement("Filter") final Filter filter) { |
| 32 | + return new MapAppender(name, filter); |
| 33 | + } |
| 34 | + |
| 35 | + @Override |
| 36 | + public void append(LogEvent event) { |
| 37 | + if (event.getLevel() |
| 38 | + .isLessSpecificThan(Level.WARN)) { |
| 39 | + error("Unable to log less than WARN level."); |
| 40 | + return; |
| 41 | + } |
| 42 | + eventMap.put(Instant.now() |
| 43 | + .toString(), event); |
| 44 | + } |
| 45 | + |
| 46 | + public ConcurrentMap<String, LogEvent> getEventMap() { |
| 47 | + return eventMap; |
| 48 | + } |
| 49 | + |
| 50 | + public void setEventMap(ConcurrentMap<String, LogEvent> eventMap) { |
| 51 | + this.eventMap = eventMap; |
| 52 | + } |
| 53 | + |
| 54 | +} |
0 commit comments