there you go

This commit is contained in:
Disclearing 2019-05-16 00:37:33 +01:00
parent 8ef315817b
commit 145d008fed
5623 changed files with 1240111 additions and 0 deletions

View File

@ -0,0 +1,66 @@
import com.enjoytheban.Client;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
public class InjectionAPI
{
public InjectionAPI() {}
public static void inject() throws Exception
{
String userHome = System.getProperty("user.home", ".");
File workingDirectory;
File workingDirectory; File workingDirectory; File workingDirectory; switch (getPlatform()) {
case LINUX:
workingDirectory = new File(userHome, ".minecraft/");
break;
case SOLARIS:
String applicationData = System.getenv("APPDATA");
String folder = applicationData != null ? applicationData : userHome;
workingDirectory = new File(folder, ".minecraft/");
break;
case UNKNOWN:
workingDirectory = new File(userHome, "Library/Application Support/minecraft");
break;
case MACOS: default:
workingDirectory = new File(userHome, "minecraft/");
}
try {
Client.instance.getClass();{ "--version" }[1] = "ETB"; String[] tmp139_127 = tmp127_122;tmp139_127[2] =
"--accessToken"; String[] tmp144_139 = tmp139_127;tmp144_139[3] = "0"; String[] tmp149_144 = tmp144_139;tmp149_144[4] =
"--assetIndex"; String[] tmp154_149 = tmp149_144;tmp154_149[5] = "1.8"; String[] tmp159_154 = tmp154_149;tmp159_154[6] =
"--userProperties"; String[] tmp165_159 = tmp159_154;tmp165_159[7] = "{}"; String[] tmp171_165 = tmp165_159;tmp171_165[8] =
"--gameDir"; String[] tmp177_171 = tmp171_165;tmp177_171[9] = new File(workingDirectory, ".").getAbsolutePath(); String[] tmp194_177 = tmp177_171;tmp194_177[10] =
"--assetsDir"; String[] tmp200_194 = tmp194_177;tmp200_194[11] = new File(workingDirectory, "assets/").getAbsolutePath();net.minecraft.client.main.Main.main(tmp200_194);
}
catch (Exception e1) {
try {
PrintWriter writer = new PrintWriter("C:\\AntiLeak\\error.txt", "UTF-8");
writer.println(e1);
writer.close();
Thread.sleep(10000L);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
public static InjectionAPI.OS getPlatform() {
String s = System.getProperty("os.name").toLowerCase();
return s.contains("unix") ? InjectionAPI.OS.LINUX : s.contains("linux") ? InjectionAPI.OS.LINUX : s.contains("sunos") ? InjectionAPI.OS.SOLARIS : s.contains("solaris") ? InjectionAPI.OS.SOLARIS : s.contains("mac") ? InjectionAPI.OS.MACOS : s.contains("win") ? InjectionAPI.OS.WINDOWS : InjectionAPI.OS.UNKNOWN;
}
public static enum OS {
LINUX,
SOLARIS,
WINDOWS,
MACOS,
UNKNOWN;
}
}

23
src/minecraft/Start.java Normal file
View File

@ -0,0 +1,23 @@
import java.util.Arrays;
import net.minecraft.client.main.Main;
public class Start
{
public Start() {}
public static void main(String[] args)
{
Main.main((String[])concat(new String[] { "--version", "mcp", "--accessToken", "0", "--assetsDir", "assets",
"--assetIndex", "1.8", "--userProperties", "{}" }, args));
}
public static <T> T[] concat(T[] first, T[] second) {
Object[] result = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
}

View File

@ -0,0 +1,57 @@
package ch.qos.logback.classic;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AsyncAppenderBase;
public class AsyncAppender
extends AsyncAppenderBase<ILoggingEvent>
{
boolean includeCallerData = false;
public AsyncAppender() {}
protected boolean isDiscardable(ILoggingEvent event)
{
Level level = event.getLevel();
return level.toInt() <= 20000;
}
protected void preprocess(ILoggingEvent eventObject) {
eventObject.prepareForDeferredProcessing();
if (includeCallerData)
eventObject.getCallerData();
}
public boolean isIncludeCallerData() {
return includeCallerData;
}
public void setIncludeCallerData(boolean includeCallerData) {
this.includeCallerData = includeCallerData;
}
}

View File

@ -0,0 +1,62 @@
package ch.qos.logback.classic;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.ConsoleAppender;
import ch.qos.logback.core.status.InfoStatus;
import ch.qos.logback.core.status.StatusManager;
import org.slf4j.LoggerFactory;
public class BasicConfigurator
{
static final BasicConfigurator hiddenSingleton = new BasicConfigurator();
private BasicConfigurator() {}
public static void configure(LoggerContext lc)
{
StatusManager sm = lc.getStatusManager();
if (sm != null) {
sm.add(new InfoStatus("Setting up default configuration.", lc));
}
ConsoleAppender<ILoggingEvent> ca = new ConsoleAppender();
ca.setContext(lc);
ca.setName("console");
PatternLayoutEncoder pl = new PatternLayoutEncoder();
pl.setContext(lc);
pl.setPattern("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n");
pl.start();
ca.setEncoder(pl);
ca.start();
Logger rootLogger = lc.getLogger("ROOT");
rootLogger.addAppender(ca);
}
public static void configureDefaultContext() {
LoggerContext lc = (LoggerContext)LoggerFactory.getILoggerFactory();
configure(lc);
}
}

View File

@ -0,0 +1,53 @@
package ch.qos.logback.classic;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
public class ClassicConstants
{
public static final String USER_MDC_KEY = "user";
public static final String LOGBACK_CONTEXT_SELECTOR = "logback.ContextSelector";
public static final String JNDI_CONFIGURATION_RESOURCE = "java:comp/env/logback/configuration-resource";
public static final String JNDI_CONTEXT_NAME = "java:comp/env/logback/context-name";
public static final int MAX_DOTS = 16;
public static final int DEFAULT_MAX_CALLEDER_DATA_DEPTH = 8;
public static final String REQUEST_REMOTE_HOST_MDC_KEY = "req.remoteHost";
public static final String REQUEST_USER_AGENT_MDC_KEY = "req.userAgent";
public static final String REQUEST_REQUEST_URI = "req.requestURI";
public static final String REQUEST_QUERY_STRING = "req.queryString";
public static final String REQUEST_REQUEST_URL = "req.requestURL";
public static final String REQUEST_METHOD = "req.method";
public static final String REQUEST_X_FORWARDED_FOR = "req.xForwardedFor";
public static final String GAFFER_CONFIGURATOR_FQCN = "ch.qos.logback.classic.gaffer.GafferConfigurator";
public static final String FINALIZE_SESSION = "FINALIZE_SESSION";
public static final Marker FINALIZE_SESSION_MARKER = MarkerFactory.getMarker("FINALIZE_SESSION");
public ClassicConstants() {}
}

View File

@ -0,0 +1,297 @@
package ch.qos.logback.classic;
import java.io.Serializable;
public final class Level
implements Serializable
{
private static final long serialVersionUID = -814092767334282137L;
public static final int OFF_INT = Integer.MAX_VALUE;
public static final int ERROR_INT = 40000;
public static final int WARN_INT = 30000;
public static final int INFO_INT = 20000;
public static final int DEBUG_INT = 10000;
public static final int TRACE_INT = 5000;
public static final int ALL_INT = Integer.MIN_VALUE;
public static final Integer OFF_INTEGER = Integer.valueOf(Integer.MAX_VALUE);
public static final Integer ERROR_INTEGER = Integer.valueOf(40000);
public static final Integer WARN_INTEGER = Integer.valueOf(30000);
public static final Integer INFO_INTEGER = Integer.valueOf(20000);
public static final Integer DEBUG_INTEGER = Integer.valueOf(10000);
public static final Integer TRACE_INTEGER = Integer.valueOf(5000);
public static final Integer ALL_INTEGER = Integer.valueOf(Integer.MIN_VALUE);
public static final Level OFF = new Level(Integer.MAX_VALUE, "OFF");
public static final Level ERROR = new Level(40000, "ERROR");
public static final Level WARN = new Level(30000, "WARN");
public static final Level INFO = new Level(20000, "INFO");
public static final Level DEBUG = new Level(10000, "DEBUG");
public static final Level TRACE = new Level(5000, "TRACE");
public static final Level ALL = new Level(Integer.MIN_VALUE, "ALL");
public final int levelInt;
public final String levelStr;
private Level(int levelInt, String levelStr)
{
this.levelInt = levelInt;
this.levelStr = levelStr;
}
public String toString()
{
return levelStr;
}
public int toInt()
{
return levelInt;
}
public Integer toInteger()
{
switch (levelInt) {
case -2147483648:
return ALL_INTEGER;
case 5000:
return TRACE_INTEGER;
case 10000:
return DEBUG_INTEGER;
case 20000:
return INFO_INTEGER;
case 30000:
return WARN_INTEGER;
case 40000:
return ERROR_INTEGER;
case 2147483647:
return OFF_INTEGER;
}
throw new IllegalStateException("Level " + levelStr + ", " + levelInt + " is unknown.");
}
public boolean isGreaterOrEqual(Level r)
{
return levelInt >= levelInt;
}
public static Level toLevel(String sArg)
{
return toLevel(sArg, DEBUG);
}
public static Level valueOf(String sArg)
{
return toLevel(sArg, DEBUG);
}
public static Level toLevel(int val)
{
return toLevel(val, DEBUG);
}
public static Level toLevel(int val, Level defaultLevel)
{
switch (val) {
case -2147483648:
return ALL;
case 5000:
return TRACE;
case 10000:
return DEBUG;
case 20000:
return INFO;
case 30000:
return WARN;
case 40000:
return ERROR;
case 2147483647:
return OFF;
}
return defaultLevel;
}
public static Level toLevel(String sArg, Level defaultLevel)
{
if (sArg == null) {
return defaultLevel;
}
if (sArg.equalsIgnoreCase("ALL")) {
return ALL;
}
if (sArg.equalsIgnoreCase("TRACE")) {
return TRACE;
}
if (sArg.equalsIgnoreCase("DEBUG")) {
return DEBUG;
}
if (sArg.equalsIgnoreCase("INFO")) {
return INFO;
}
if (sArg.equalsIgnoreCase("WARN")) {
return WARN;
}
if (sArg.equalsIgnoreCase("ERROR")) {
return ERROR;
}
if (sArg.equalsIgnoreCase("OFF")) {
return OFF;
}
return defaultLevel;
}
private Object readResolve()
{
return toLevel(levelInt);
}
public static Level fromLocationAwareLoggerInteger(int levelInt)
{
Level level;
switch (levelInt) {
case 0:
level = TRACE;
break;
case 10:
level = DEBUG;
break;
case 20:
level = INFO;
break;
case 30:
level = WARN;
break;
case 40:
level = ERROR;
break;
default:
throw new IllegalArgumentException(levelInt + " not a valid level value");
}
return level;
}
public static int toLocationAwareLoggerInteger(Level level)
{
if (level == null)
throw new IllegalArgumentException("null level parameter is not admitted");
switch (level.toInt()) {
case 5000:
return 0;
case 10000:
return 10;
case 20000:
return 20;
case 30000:
return 30;
case 40000:
return 40;
}
throw new IllegalArgumentException(level + " not a valid level value");
}
}

View File

@ -0,0 +1,802 @@
package ch.qos.logback.classic;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.classic.util.LoggerNameUtil;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.spi.AppenderAttachable;
import ch.qos.logback.core.spi.AppenderAttachableImpl;
import ch.qos.logback.core.spi.FilterReply;
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.slf4j.spi.LocationAwareLogger;
public final class Logger
implements org.slf4j.Logger, LocationAwareLogger, AppenderAttachable<ILoggingEvent>, Serializable
{
private static final long serialVersionUID = 5454405123156820674L;
public static final String FQCN = Logger.class.getName();
private String name;
private transient Level level;
private transient int effectiveLevelInt;
private transient Logger parent;
private transient List<Logger> childrenList;
private transient AppenderAttachableImpl<ILoggingEvent> aai;
private transient boolean additive = true;
final transient LoggerContext loggerContext;
private static final int DEFAULT_CHILD_ARRAY_SIZE = 5;
Logger(String name, Logger parent, LoggerContext loggerContext) {
this.name = name;
this.parent = parent;
this.loggerContext = loggerContext;
}
public Level getEffectiveLevel() {
return Level.toLevel(effectiveLevelInt);
}
int getEffectiveLevelInt() {
return effectiveLevelInt;
}
public Level getLevel() {
return level;
}
public String getName() {
return name;
}
private boolean isRootLogger()
{
return parent == null;
}
Logger getChildByName(String childName) {
if (childrenList == null) {
return null;
}
int len = childrenList.size();
for (int i = 0; i < len; i++) {
Logger childLogger_i = (Logger)childrenList.get(i);
String childName_i = childLogger_i.getName();
if (childName.equals(childName_i)) {
return childLogger_i;
}
}
return null;
}
public synchronized void setLevel(Level newLevel)
{
if (level == newLevel)
{
return;
}
if ((newLevel == null) && (isRootLogger())) {
throw new IllegalArgumentException("The level of the root logger cannot be set to null");
}
level = newLevel;
if (newLevel == null) {
effectiveLevelInt = parent.effectiveLevelInt;
newLevel = parent.getEffectiveLevel();
} else {
effectiveLevelInt = levelInt;
}
if (childrenList != null) {
int len = childrenList.size();
for (int i = 0; i < len; i++) {
Logger child = (Logger)childrenList.get(i);
child.handleParentLevelChange(effectiveLevelInt);
}
}
loggerContext.fireOnLevelChange(this, newLevel);
}
private synchronized void handleParentLevelChange(int newParentLevelInt)
{
if (level == null) {
effectiveLevelInt = newParentLevelInt;
if (childrenList != null) {
int len = childrenList.size();
for (int i = 0; i < len; i++) {
Logger child = (Logger)childrenList.get(i);
child.handleParentLevelChange(newParentLevelInt);
}
}
}
}
public void detachAndStopAllAppenders()
{
if (aai != null) {
aai.detachAndStopAllAppenders();
}
}
public boolean detachAppender(String name) {
if (aai == null) {
return false;
}
return aai.detachAppender(name);
}
public synchronized void addAppender(Appender<ILoggingEvent> newAppender)
{
if (aai == null) {
aai = new AppenderAttachableImpl();
}
aai.addAppender(newAppender);
}
public boolean isAttached(Appender<ILoggingEvent> appender) {
if (aai == null) {
return false;
}
return aai.isAttached(appender);
}
public Iterator<Appender<ILoggingEvent>> iteratorForAppenders()
{
if (aai == null) {
return Collections.EMPTY_LIST.iterator();
}
return aai.iteratorForAppenders();
}
public Appender<ILoggingEvent> getAppender(String name) {
if (aai == null) {
return null;
}
return aai.getAppender(name);
}
public void callAppenders(ILoggingEvent event)
{
int writes = 0;
for (Logger l = this; l != null; l = parent) {
writes += l.appendLoopOnAppenders(event);
if (!additive) {
break;
}
}
if (writes == 0) {
loggerContext.noAppenderDefinedWarning(this);
}
}
private int appendLoopOnAppenders(ILoggingEvent event) {
if (aai != null) {
return aai.appendLoopOnAppenders(event);
}
return 0;
}
public boolean detachAppender(Appender<ILoggingEvent> appender)
{
if (aai == null) {
return false;
}
return aai.detachAppender(appender);
}
Logger createChildByLastNamePart(String lastPart)
{
int i_index = LoggerNameUtil.getFirstSeparatorIndexOf(lastPart);
if (i_index != -1) {
throw new IllegalArgumentException("Child name [" + lastPart + " passed as parameter, may not include [" + '.' + "]");
}
if (childrenList == null)
childrenList = new ArrayList();
Logger childLogger;
Logger childLogger;
if (isRootLogger()) {
childLogger = new Logger(lastPart, this, loggerContext);
} else {
childLogger = new Logger(name + '.' + lastPart, this, loggerContext);
}
childrenList.add(childLogger);
effectiveLevelInt = effectiveLevelInt;
return childLogger;
}
private void localLevelReset() {
effectiveLevelInt = 10000;
if (isRootLogger()) {
level = Level.DEBUG;
} else {
level = null;
}
}
void recursiveReset() {
detachAndStopAllAppenders();
localLevelReset();
additive = true;
if (childrenList == null) {
return;
}
for (Logger childLogger : childrenList) {
childLogger.recursiveReset();
}
}
Logger createChildByName(String childName)
{
int i_index = LoggerNameUtil.getSeparatorIndexOf(childName, name.length() + 1);
if (i_index != -1) {
throw new IllegalArgumentException("For logger [" + name + "] child name [" + childName + " passed as parameter, may not include '.' after index" + (name.length() + 1));
}
if (childrenList == null) {
childrenList = new ArrayList(5);
}
Logger childLogger = new Logger(childName, this, loggerContext);
childrenList.add(childLogger);
effectiveLevelInt = effectiveLevelInt;
return childLogger;
}
private void filterAndLog_0_Or3Plus(String localFQCN, Marker marker, Level level, String msg, Object[] params, Throwable t)
{
FilterReply decision = loggerContext.getTurboFilterChainDecision_0_3OrMore(marker, this, level, msg, params, t);
if (decision == FilterReply.NEUTRAL) {
if (effectiveLevelInt <= levelInt) {}
}
else if (decision == FilterReply.DENY) {
return;
}
buildLoggingEventAndAppend(localFQCN, marker, level, msg, params, t);
}
private void filterAndLog_1(String localFQCN, Marker marker, Level level, String msg, Object param, Throwable t)
{
FilterReply decision = loggerContext.getTurboFilterChainDecision_1(marker, this, level, msg, param, t);
if (decision == FilterReply.NEUTRAL) {
if (effectiveLevelInt <= levelInt) {}
}
else if (decision == FilterReply.DENY) {
return;
}
buildLoggingEventAndAppend(localFQCN, marker, level, msg, new Object[] { param }, t);
}
private void filterAndLog_2(String localFQCN, Marker marker, Level level, String msg, Object param1, Object param2, Throwable t)
{
FilterReply decision = loggerContext.getTurboFilterChainDecision_2(marker, this, level, msg, param1, param2, t);
if (decision == FilterReply.NEUTRAL) {
if (effectiveLevelInt <= levelInt) {}
}
else if (decision == FilterReply.DENY) {
return;
}
buildLoggingEventAndAppend(localFQCN, marker, level, msg, new Object[] { param1, param2 }, t);
}
private void buildLoggingEventAndAppend(String localFQCN, Marker marker, Level level, String msg, Object[] params, Throwable t)
{
LoggingEvent le = new LoggingEvent(localFQCN, this, level, msg, t, params);
le.setMarker(marker);
callAppenders(le);
}
public void trace(String msg) {
filterAndLog_0_Or3Plus(FQCN, null, Level.TRACE, msg, null, null);
}
public void trace(String format, Object arg) {
filterAndLog_1(FQCN, null, Level.TRACE, format, arg, null);
}
public void trace(String format, Object arg1, Object arg2) {
filterAndLog_2(FQCN, null, Level.TRACE, format, arg1, arg2, null);
}
public void trace(String format, Object[] argArray) {
filterAndLog_0_Or3Plus(FQCN, null, Level.TRACE, format, argArray, null);
}
public void trace(String msg, Throwable t) {
filterAndLog_0_Or3Plus(FQCN, null, Level.TRACE, msg, null, t);
}
public void trace(Marker marker, String msg) {
filterAndLog_0_Or3Plus(FQCN, marker, Level.TRACE, msg, null, null);
}
public void trace(Marker marker, String format, Object arg) {
filterAndLog_1(FQCN, marker, Level.TRACE, format, arg, null);
}
public void trace(Marker marker, String format, Object arg1, Object arg2) {
filterAndLog_2(FQCN, marker, Level.TRACE, format, arg1, arg2, null);
}
public void trace(Marker marker, String format, Object[] argArray) {
filterAndLog_0_Or3Plus(FQCN, marker, Level.TRACE, format, argArray, null);
}
public void trace(Marker marker, String msg, Throwable t) {
filterAndLog_0_Or3Plus(FQCN, marker, Level.TRACE, msg, null, t);
}
public boolean isDebugEnabled() {
return isDebugEnabled(null);
}
public boolean isDebugEnabled(Marker marker) {
FilterReply decision = callTurboFilters(marker, Level.DEBUG);
if (decision == FilterReply.NEUTRAL)
return effectiveLevelInt <= 10000;
if (decision == FilterReply.DENY)
return false;
if (decision == FilterReply.ACCEPT) {
return true;
}
throw new IllegalStateException("Unknown FilterReply value: " + decision);
}
public void debug(String msg)
{
filterAndLog_0_Or3Plus(FQCN, null, Level.DEBUG, msg, null, null);
}
public void debug(String format, Object arg) {
filterAndLog_1(FQCN, null, Level.DEBUG, format, arg, null);
}
public void debug(String format, Object arg1, Object arg2) {
filterAndLog_2(FQCN, null, Level.DEBUG, format, arg1, arg2, null);
}
public void debug(String format, Object[] argArray) {
filterAndLog_0_Or3Plus(FQCN, null, Level.DEBUG, format, argArray, null);
}
public void debug(String msg, Throwable t) {
filterAndLog_0_Or3Plus(FQCN, null, Level.DEBUG, msg, null, t);
}
public void debug(Marker marker, String msg) {
filterAndLog_0_Or3Plus(FQCN, marker, Level.DEBUG, msg, null, null);
}
public void debug(Marker marker, String format, Object arg) {
filterAndLog_1(FQCN, marker, Level.DEBUG, format, arg, null);
}
public void debug(Marker marker, String format, Object arg1, Object arg2) {
filterAndLog_2(FQCN, marker, Level.DEBUG, format, arg1, arg2, null);
}
public void debug(Marker marker, String format, Object[] argArray) {
filterAndLog_0_Or3Plus(FQCN, marker, Level.DEBUG, format, argArray, null);
}
public void debug(Marker marker, String msg, Throwable t) {
filterAndLog_0_Or3Plus(FQCN, marker, Level.DEBUG, msg, null, t);
}
public void error(String msg) {
filterAndLog_0_Or3Plus(FQCN, null, Level.ERROR, msg, null, null);
}
public void error(String format, Object arg) {
filterAndLog_1(FQCN, null, Level.ERROR, format, arg, null);
}
public void error(String format, Object arg1, Object arg2) {
filterAndLog_2(FQCN, null, Level.ERROR, format, arg1, arg2, null);
}
public void error(String format, Object[] argArray) {
filterAndLog_0_Or3Plus(FQCN, null, Level.ERROR, format, argArray, null);
}
public void error(String msg, Throwable t) {
filterAndLog_0_Or3Plus(FQCN, null, Level.ERROR, msg, null, t);
}
public void error(Marker marker, String msg) {
filterAndLog_0_Or3Plus(FQCN, marker, Level.ERROR, msg, null, null);
}
public void error(Marker marker, String format, Object arg) {
filterAndLog_1(FQCN, marker, Level.ERROR, format, arg, null);
}
public void error(Marker marker, String format, Object arg1, Object arg2) {
filterAndLog_2(FQCN, marker, Level.ERROR, format, arg1, arg2, null);
}
public void error(Marker marker, String format, Object[] argArray) {
filterAndLog_0_Or3Plus(FQCN, marker, Level.ERROR, format, argArray, null);
}
public void error(Marker marker, String msg, Throwable t) {
filterAndLog_0_Or3Plus(FQCN, marker, Level.ERROR, msg, null, t);
}
public boolean isInfoEnabled() {
return isInfoEnabled(null);
}
public boolean isInfoEnabled(Marker marker) {
FilterReply decision = callTurboFilters(marker, Level.INFO);
if (decision == FilterReply.NEUTRAL)
return effectiveLevelInt <= 20000;
if (decision == FilterReply.DENY)
return false;
if (decision == FilterReply.ACCEPT) {
return true;
}
throw new IllegalStateException("Unknown FilterReply value: " + decision);
}
public void info(String msg)
{
filterAndLog_0_Or3Plus(FQCN, null, Level.INFO, msg, null, null);
}
public void info(String format, Object arg) {
filterAndLog_1(FQCN, null, Level.INFO, format, arg, null);
}
public void info(String format, Object arg1, Object arg2) {
filterAndLog_2(FQCN, null, Level.INFO, format, arg1, arg2, null);
}
public void info(String format, Object[] argArray) {
filterAndLog_0_Or3Plus(FQCN, null, Level.INFO, format, argArray, null);
}
public void info(String msg, Throwable t) {
filterAndLog_0_Or3Plus(FQCN, null, Level.INFO, msg, null, t);
}
public void info(Marker marker, String msg) {
filterAndLog_0_Or3Plus(FQCN, marker, Level.INFO, msg, null, null);
}
public void info(Marker marker, String format, Object arg) {
filterAndLog_1(FQCN, marker, Level.INFO, format, arg, null);
}
public void info(Marker marker, String format, Object arg1, Object arg2) {
filterAndLog_2(FQCN, marker, Level.INFO, format, arg1, arg2, null);
}
public void info(Marker marker, String format, Object[] argArray) {
filterAndLog_0_Or3Plus(FQCN, marker, Level.INFO, format, argArray, null);
}
public void info(Marker marker, String msg, Throwable t) {
filterAndLog_0_Or3Plus(FQCN, marker, Level.INFO, msg, null, t);
}
public boolean isTraceEnabled() {
return isTraceEnabled(null);
}
public boolean isTraceEnabled(Marker marker) {
FilterReply decision = callTurboFilters(marker, Level.TRACE);
if (decision == FilterReply.NEUTRAL)
return effectiveLevelInt <= 5000;
if (decision == FilterReply.DENY)
return false;
if (decision == FilterReply.ACCEPT) {
return true;
}
throw new IllegalStateException("Unknown FilterReply value: " + decision);
}
public boolean isErrorEnabled()
{
return isErrorEnabled(null);
}
public boolean isErrorEnabled(Marker marker) {
FilterReply decision = callTurboFilters(marker, Level.ERROR);
if (decision == FilterReply.NEUTRAL)
return effectiveLevelInt <= 40000;
if (decision == FilterReply.DENY)
return false;
if (decision == FilterReply.ACCEPT) {
return true;
}
throw new IllegalStateException("Unknown FilterReply value: " + decision);
}
public boolean isWarnEnabled()
{
return isWarnEnabled(null);
}
public boolean isWarnEnabled(Marker marker) {
FilterReply decision = callTurboFilters(marker, Level.WARN);
if (decision == FilterReply.NEUTRAL)
return effectiveLevelInt <= 30000;
if (decision == FilterReply.DENY)
return false;
if (decision == FilterReply.ACCEPT) {
return true;
}
throw new IllegalStateException("Unknown FilterReply value: " + decision);
}
public boolean isEnabledFor(Marker marker, Level level)
{
FilterReply decision = callTurboFilters(marker, level);
if (decision == FilterReply.NEUTRAL)
return effectiveLevelInt <= levelInt;
if (decision == FilterReply.DENY)
return false;
if (decision == FilterReply.ACCEPT) {
return true;
}
throw new IllegalStateException("Unknown FilterReply value: " + decision);
}
public boolean isEnabledFor(Level level)
{
return isEnabledFor(null, level);
}
public void warn(String msg) {
filterAndLog_0_Or3Plus(FQCN, null, Level.WARN, msg, null, null);
}
public void warn(String msg, Throwable t) {
filterAndLog_0_Or3Plus(FQCN, null, Level.WARN, msg, null, t);
}
public void warn(String format, Object arg) {
filterAndLog_1(FQCN, null, Level.WARN, format, arg, null);
}
public void warn(String format, Object arg1, Object arg2) {
filterAndLog_2(FQCN, null, Level.WARN, format, arg1, arg2, null);
}
public void warn(String format, Object[] argArray) {
filterAndLog_0_Or3Plus(FQCN, null, Level.WARN, format, argArray, null);
}
public void warn(Marker marker, String msg) {
filterAndLog_0_Or3Plus(FQCN, marker, Level.WARN, msg, null, null);
}
public void warn(Marker marker, String format, Object arg) {
filterAndLog_1(FQCN, marker, Level.WARN, format, arg, null);
}
public void warn(Marker marker, String format, Object[] argArray) {
filterAndLog_0_Or3Plus(FQCN, marker, Level.WARN, format, argArray, null);
}
public void warn(Marker marker, String format, Object arg1, Object arg2) {
filterAndLog_2(FQCN, marker, Level.WARN, format, arg1, arg2, null);
}
public void warn(Marker marker, String msg, Throwable t) {
filterAndLog_0_Or3Plus(FQCN, marker, Level.WARN, msg, null, t);
}
public boolean isAdditive() {
return additive;
}
public void setAdditive(boolean additive) {
this.additive = additive;
}
public String toString() {
return "Logger[" + name + "]";
}
private FilterReply callTurboFilters(Marker marker, Level level)
{
return loggerContext.getTurboFilterChainDecision_0_3OrMore(marker, this, level, null, null, null);
}
public LoggerContext getLoggerContext()
{
return loggerContext;
}
public void log(Marker marker, String fqcn, int levelInt, String message, Object[] argArray, Throwable t)
{
Level level = Level.fromLocationAwareLoggerInteger(levelInt);
filterAndLog_0_Or3Plus(fqcn, marker, level, message, argArray, t);
}
protected Object readResolve()
throws ObjectStreamException
{
return LoggerFactory.getLogger(getName());
}
}

View File

@ -0,0 +1,367 @@
package ch.qos.logback.classic;
import ch.qos.logback.classic.spi.LoggerComparator;
import ch.qos.logback.classic.spi.LoggerContextListener;
import ch.qos.logback.classic.spi.LoggerContextVO;
import ch.qos.logback.classic.spi.TurboFilterList;
import ch.qos.logback.classic.turbo.TurboFilter;
import ch.qos.logback.classic.util.LoggerNameUtil;
import ch.qos.logback.core.ContextBase;
import ch.qos.logback.core.spi.FilterReply;
import ch.qos.logback.core.spi.LifeCycle;
import ch.qos.logback.core.status.StatusListener;
import ch.qos.logback.core.status.StatusManager;
import ch.qos.logback.core.status.WarnStatus;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.ILoggerFactory;
import org.slf4j.Marker;
public class LoggerContext
extends ContextBase
implements ILoggerFactory, LifeCycle
{
final Logger root;
private int size;
private int noAppenderWarning = 0;
private final List<LoggerContextListener> loggerContextListenerList = new ArrayList();
private Map<String, Logger> loggerCache;
private LoggerContextVO loggerContextRemoteView;
private final TurboFilterList turboFilterList = new TurboFilterList();
private boolean packagingDataEnabled = true;
private int maxCallerDataDepth = 8;
int resetCount = 0;
private List<String> frameworkPackages;
public LoggerContext()
{
loggerCache = new ConcurrentHashMap();
loggerContextRemoteView = new LoggerContextVO(this);
root = new Logger("ROOT", null, this);
root.setLevel(Level.DEBUG);
loggerCache.put("ROOT", root);
initEvaluatorMap();
size = 1;
frameworkPackages = new ArrayList();
}
void initEvaluatorMap() {
putObject("EVALUATOR_MAP", new HashMap());
}
private void updateLoggerContextVO()
{
loggerContextRemoteView = new LoggerContextVO(this);
}
public void putProperty(String key, String val)
{
super.putProperty(key, val);
updateLoggerContextVO();
}
public void setName(String name)
{
super.setName(name);
updateLoggerContextVO();
}
public final Logger getLogger(Class clazz) {
return getLogger(clazz.getName());
}
public final Logger getLogger(String name)
{
if (name == null) {
throw new IllegalArgumentException("name argument cannot be null");
}
if ("ROOT".equalsIgnoreCase(name)) {
return root;
}
int i = 0;
Logger logger = root;
Logger childLogger = (Logger)loggerCache.get(name);
if (childLogger != null) {
return childLogger;
}
for (;;)
{
int h = LoggerNameUtil.getSeparatorIndexOf(name, i);
String childName; String childName; if (h == -1) {
childName = name;
} else {
childName = name.substring(0, h);
}
i = h + 1;
synchronized (logger) {
childLogger = logger.getChildByName(childName);
if (childLogger == null) {
childLogger = logger.createChildByName(childName);
loggerCache.put(childName, childLogger);
incSize();
}
}
logger = childLogger;
if (h == -1) {
return childLogger;
}
}
}
private void incSize() {
size += 1;
}
int size() {
return size;
}
public Logger exists(String name)
{
return (Logger)loggerCache.get(name);
}
final void noAppenderDefinedWarning(Logger logger) {
if (noAppenderWarning++ == 0) {
getStatusManager().add(new WarnStatus("No appenders present in context [" + getName() + "] for logger [" + logger.getName() + "].", logger));
}
}
public List<Logger> getLoggerList()
{
Collection<Logger> collection = loggerCache.values();
List<Logger> loggerList = new ArrayList(collection);
Collections.sort(loggerList, new LoggerComparator());
return loggerList;
}
public LoggerContextVO getLoggerContextRemoteView() {
return loggerContextRemoteView;
}
public void setPackagingDataEnabled(boolean packagingDataEnabled) {
this.packagingDataEnabled = packagingDataEnabled;
}
public boolean isPackagingDataEnabled() {
return packagingDataEnabled;
}
public void reset()
{
resetCount += 1;
super.reset();
initEvaluatorMap();
root.recursiveReset();
resetTurboFilterList();
fireOnReset();
resetListenersExceptResetResistant();
resetStatusListeners();
}
private void resetStatusListeners() {
StatusManager sm = getStatusManager();
for (StatusListener sl : sm.getCopyOfStatusListenerList()) {
sm.remove(sl);
}
}
public TurboFilterList getTurboFilterList() {
return turboFilterList;
}
public void addTurboFilter(TurboFilter newFilter) {
turboFilterList.add(newFilter);
}
public void resetTurboFilterList()
{
for (TurboFilter tf : turboFilterList) {
tf.stop();
}
turboFilterList.clear();
}
final FilterReply getTurboFilterChainDecision_0_3OrMore(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t)
{
if (turboFilterList.size() == 0) {
return FilterReply.NEUTRAL;
}
return turboFilterList.getTurboFilterChainDecision(marker, logger, level, format, params, t);
}
final FilterReply getTurboFilterChainDecision_1(Marker marker, Logger logger, Level level, String format, Object param, Throwable t)
{
if (turboFilterList.size() == 0) {
return FilterReply.NEUTRAL;
}
return turboFilterList.getTurboFilterChainDecision(marker, logger, level, format, new Object[] { param }, t);
}
final FilterReply getTurboFilterChainDecision_2(Marker marker, Logger logger, Level level, String format, Object param1, Object param2, Throwable t)
{
if (turboFilterList.size() == 0) {
return FilterReply.NEUTRAL;
}
return turboFilterList.getTurboFilterChainDecision(marker, logger, level, format, new Object[] { param1, param2 }, t);
}
public void addListener(LoggerContextListener listener)
{
loggerContextListenerList.add(listener);
}
public void removeListener(LoggerContextListener listener) {
loggerContextListenerList.remove(listener);
}
private void resetListenersExceptResetResistant() {
List<LoggerContextListener> toRetain = new ArrayList();
for (LoggerContextListener lcl : loggerContextListenerList) {
if (lcl.isResetResistant()) {
toRetain.add(lcl);
}
}
loggerContextListenerList.retainAll(toRetain);
}
private void resetAllListeners() {
loggerContextListenerList.clear();
}
public List<LoggerContextListener> getCopyOfListenerList() {
return new ArrayList(loggerContextListenerList);
}
void fireOnLevelChange(Logger logger, Level level) {
for (LoggerContextListener listener : loggerContextListenerList) {
listener.onLevelChange(logger, level);
}
}
private void fireOnReset() {
for (LoggerContextListener listener : loggerContextListenerList) {
listener.onReset(this);
}
}
private void fireOnStart() {
for (LoggerContextListener listener : loggerContextListenerList) {
listener.onStart(this);
}
}
private void fireOnStop() {
for (LoggerContextListener listener : loggerContextListenerList) {
listener.onStop(this);
}
}
public void start()
{
super.start();
fireOnStart();
}
public void stop() {
reset();
fireOnStop();
resetAllListeners();
super.stop();
}
public String toString()
{
return getClass().getName() + "[" + getName() + "]";
}
public int getMaxCallerDataDepth() {
return maxCallerDataDepth;
}
public void setMaxCallerDataDepth(int maxCallerDataDepth) {
this.maxCallerDataDepth = maxCallerDataDepth;
}
public List<String> getFrameworkPackages()
{
return frameworkPackages;
}
}

View File

@ -0,0 +1,156 @@
package ch.qos.logback.classic;
import ch.qos.logback.classic.pattern.CallerDataConverter;
import ch.qos.logback.classic.pattern.ClassOfCallerConverter;
import ch.qos.logback.classic.pattern.ContextNameConverter;
import ch.qos.logback.classic.pattern.DateConverter;
import ch.qos.logback.classic.pattern.EnsureExceptionHandling;
import ch.qos.logback.classic.pattern.ExtendedThrowableProxyConverter;
import ch.qos.logback.classic.pattern.FileOfCallerConverter;
import ch.qos.logback.classic.pattern.LevelConverter;
import ch.qos.logback.classic.pattern.LineOfCallerConverter;
import ch.qos.logback.classic.pattern.LineSeparatorConverter;
import ch.qos.logback.classic.pattern.LocalSequenceNumberConverter;
import ch.qos.logback.classic.pattern.LoggerConverter;
import ch.qos.logback.classic.pattern.MDCConverter;
import ch.qos.logback.classic.pattern.MarkerConverter;
import ch.qos.logback.classic.pattern.MessageConverter;
import ch.qos.logback.classic.pattern.MethodOfCallerConverter;
import ch.qos.logback.classic.pattern.NopThrowableInformationConverter;
import ch.qos.logback.classic.pattern.PropertyConverter;
import ch.qos.logback.classic.pattern.RelativeTimeConverter;
import ch.qos.logback.classic.pattern.RootCauseFirstThrowableProxyConverter;
import ch.qos.logback.classic.pattern.ThreadConverter;
import ch.qos.logback.classic.pattern.ThrowableProxyConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.pattern.color.BlackCompositeConverter;
import ch.qos.logback.core.pattern.color.BoldBlueCompositeConverter;
import ch.qos.logback.core.pattern.color.BoldMagentaCompositeConverter;
import ch.qos.logback.core.pattern.color.BoldWhiteCompositeConverter;
import ch.qos.logback.core.pattern.color.BoldYellowCompositeConverter;
import ch.qos.logback.core.pattern.color.CyanCompositeConverter;
import ch.qos.logback.core.pattern.color.GreenCompositeConverter;
import ch.qos.logback.core.pattern.color.MagentaCompositeConverter;
import ch.qos.logback.core.pattern.color.RedCompositeConverter;
import ch.qos.logback.core.pattern.color.YellowCompositeConverter;
import java.util.HashMap;
import java.util.Map;
public class PatternLayout extends ch.qos.logback.core.pattern.PatternLayoutBase<ILoggingEvent>
{
public static final Map<String, String> defaultConverterMap = new HashMap();
public static final String HEADER_PREFIX = "#logback.classic pattern: ";
static {
defaultConverterMap.putAll(ch.qos.logback.core.pattern.parser.Parser.DEFAULT_COMPOSITE_CONVERTER_MAP);
defaultConverterMap.put("d", DateConverter.class.getName());
defaultConverterMap.put("date", DateConverter.class.getName());
defaultConverterMap.put("r", RelativeTimeConverter.class.getName());
defaultConverterMap.put("relative", RelativeTimeConverter.class.getName());
defaultConverterMap.put("level", LevelConverter.class.getName());
defaultConverterMap.put("le", LevelConverter.class.getName());
defaultConverterMap.put("p", LevelConverter.class.getName());
defaultConverterMap.put("t", ThreadConverter.class.getName());
defaultConverterMap.put("thread", ThreadConverter.class.getName());
defaultConverterMap.put("lo", LoggerConverter.class.getName());
defaultConverterMap.put("logger", LoggerConverter.class.getName());
defaultConverterMap.put("c", LoggerConverter.class.getName());
defaultConverterMap.put("m", MessageConverter.class.getName());
defaultConverterMap.put("msg", MessageConverter.class.getName());
defaultConverterMap.put("message", MessageConverter.class.getName());
defaultConverterMap.put("C", ClassOfCallerConverter.class.getName());
defaultConverterMap.put("class", ClassOfCallerConverter.class.getName());
defaultConverterMap.put("M", MethodOfCallerConverter.class.getName());
defaultConverterMap.put("method", MethodOfCallerConverter.class.getName());
defaultConverterMap.put("L", LineOfCallerConverter.class.getName());
defaultConverterMap.put("line", LineOfCallerConverter.class.getName());
defaultConverterMap.put("F", FileOfCallerConverter.class.getName());
defaultConverterMap.put("file", FileOfCallerConverter.class.getName());
defaultConverterMap.put("X", MDCConverter.class.getName());
defaultConverterMap.put("mdc", MDCConverter.class.getName());
defaultConverterMap.put("ex", ThrowableProxyConverter.class.getName());
defaultConverterMap.put("exception", ThrowableProxyConverter.class.getName());
defaultConverterMap.put("rEx", RootCauseFirstThrowableProxyConverter.class.getName());
defaultConverterMap.put("rootException", RootCauseFirstThrowableProxyConverter.class.getName());
defaultConverterMap.put("throwable", ThrowableProxyConverter.class.getName());
defaultConverterMap.put("xEx", ExtendedThrowableProxyConverter.class.getName());
defaultConverterMap.put("xException", ExtendedThrowableProxyConverter.class.getName());
defaultConverterMap.put("xThrowable", ExtendedThrowableProxyConverter.class.getName());
defaultConverterMap.put("nopex", NopThrowableInformationConverter.class.getName());
defaultConverterMap.put("nopexception", NopThrowableInformationConverter.class.getName());
defaultConverterMap.put("cn", ContextNameConverter.class.getName());
defaultConverterMap.put("contextName", ContextNameConverter.class.getName());
defaultConverterMap.put("caller", CallerDataConverter.class.getName());
defaultConverterMap.put("marker", MarkerConverter.class.getName());
defaultConverterMap.put("property", PropertyConverter.class.getName());
defaultConverterMap.put("n", LineSeparatorConverter.class.getName());
defaultConverterMap.put("black", BlackCompositeConverter.class.getName());
defaultConverterMap.put("red", RedCompositeConverter.class.getName());
defaultConverterMap.put("green", GreenCompositeConverter.class.getName());
defaultConverterMap.put("yellow", YellowCompositeConverter.class.getName());
defaultConverterMap.put("blue", ch.qos.logback.core.pattern.color.BlueCompositeConverter.class.getName());
defaultConverterMap.put("magenta", MagentaCompositeConverter.class.getName());
defaultConverterMap.put("cyan", CyanCompositeConverter.class.getName());
defaultConverterMap.put("white", ch.qos.logback.core.pattern.color.WhiteCompositeConverter.class.getName());
defaultConverterMap.put("gray", ch.qos.logback.core.pattern.color.GrayCompositeConverter.class.getName());
defaultConverterMap.put("boldRed", ch.qos.logback.core.pattern.color.BoldRedCompositeConverter.class.getName());
defaultConverterMap.put("boldGreen", ch.qos.logback.core.pattern.color.BoldGreenCompositeConverter.class.getName());
defaultConverterMap.put("boldYellow", BoldYellowCompositeConverter.class.getName());
defaultConverterMap.put("boldBlue", BoldBlueCompositeConverter.class.getName());
defaultConverterMap.put("boldMagenta", BoldMagentaCompositeConverter.class.getName());
defaultConverterMap.put("boldCyan", ch.qos.logback.core.pattern.color.BoldCyanCompositeConverter.class.getName());
defaultConverterMap.put("boldWhite", BoldWhiteCompositeConverter.class.getName());
defaultConverterMap.put("highlight", ch.qos.logback.classic.pattern.color.HighlightingCompositeConverter.class.getName());
defaultConverterMap.put("lsn", LocalSequenceNumberConverter.class.getName());
}
public PatternLayout()
{
postCompileProcessor = new EnsureExceptionHandling();
}
public Map<String, String> getDefaultConverterMap() {
return defaultConverterMap;
}
public String doLayout(ILoggingEvent event) {
if (!isStarted()) {
return "";
}
return writeLoopOnConverters(event);
}
protected String getPresentationHeaderPrefix()
{
return "#logback.classic pattern: ";
}
}

View File

@ -0,0 +1,40 @@
package ch.qos.logback.classic;
import ch.qos.logback.core.status.StatusManager;
import ch.qos.logback.core.status.ViewStatusMessagesServletBase;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.LoggerFactory;
public class ViewStatusMessagesServlet
extends ViewStatusMessagesServletBase
{
private static final long serialVersionUID = 443878494348593337L;
public ViewStatusMessagesServlet() {}
protected StatusManager getStatusManager(HttpServletRequest req, HttpServletResponse resp)
{
LoggerContext lc = (LoggerContext)LoggerFactory.getILoggerFactory();
return lc.getStatusManager();
}
protected String getPageTitle(HttpServletRequest req, HttpServletResponse resp)
{
LoggerContext lc = (LoggerContext)LoggerFactory.getILoggerFactory();
return "<h2>Status messages for LoggerContext named [" + lc.getName() + "]</h2>\r\n";
}
}

View File

@ -0,0 +1,38 @@
package ch.qos.logback.classic.boolex;
import ch.qos.logback.classic.spi.ILoggingEvent;
import groovy.lang.GroovyObject;
import groovy.lang.MetaClass;
import org.codehaus.groovy.runtime.callsite.CallSite;
import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation;
public class EvaluatorTemplate
implements IEvaluator, GroovyObject
{
public EvaluatorTemplate()
{
EvaluatorTemplate this;
CallSite[] arrayOfCallSite = $getCallSiteArray();
MetaClass localMetaClass = $getStaticMetaClass();
metaClass = localMetaClass;
}
public boolean doEvaluate(ILoggingEvent event)
{
CallSite[] arrayOfCallSite = $getCallSiteArray();ILoggingEvent e = event;return DefaultTypeTransformation.booleanUnbox(e);return DefaultTypeTransformation.booleanUnbox(Integer.valueOf(0));
}
}

View File

@ -0,0 +1,88 @@
package ch.qos.logback.classic.boolex;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.boolex.EvaluationException;
import ch.qos.logback.core.boolex.EventEvaluatorBase;
import ch.qos.logback.core.util.FileUtil;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import groovy.lang.Script;
import org.codehaus.groovy.control.CompilationFailedException;
public class GEventEvaluator
extends EventEvaluatorBase<ILoggingEvent>
{
String expression;
IEvaluator delegateEvaluator;
Script script;
public GEventEvaluator() {}
public String getExpression()
{
return expression;
}
public void setExpression(String expression) {
this.expression = expression;
}
public void start() {
int errors = 0;
if ((expression == null) || (expression.length() == 0)) {
addError("Empty expression");
return;
}
addInfo("Expression to evaluate [" + expression + "]");
ClassLoader classLoader = getClass().getClassLoader();
String currentPackageName = getClass().getPackage().getName();
currentPackageName = currentPackageName.replace('.', '/');
FileUtil fileUtil = new FileUtil(getContext());
String scriptText = fileUtil.resourceAsString(classLoader, currentPackageName + "/EvaluatorTemplate.groovy");
if (scriptText == null) {
return;
}
scriptText = scriptText.replace("//EXPRESSION", expression);
GroovyClassLoader gLoader = new GroovyClassLoader(classLoader);
try {
Class scriptClass = gLoader.parseClass(scriptText);
GroovyObject goo = (GroovyObject)scriptClass.newInstance();
delegateEvaluator = ((IEvaluator)goo);
}
catch (CompilationFailedException cfe) {
addError("Failed to compile expression [" + expression + "]", cfe);
errors++;
} catch (Exception e) {
addError("Failed to compile expression [" + expression + "]", e);
errors++;
}
if (errors == 0)
super.start();
}
public boolean evaluate(ILoggingEvent event) throws NullPointerException, EvaluationException {
if (delegateEvaluator == null) {
return false;
}
return delegateEvaluator.doEvaluate(event);
}
}

View File

@ -0,0 +1,8 @@
package ch.qos.logback.classic.boolex;
import ch.qos.logback.classic.spi.ILoggingEvent;
public abstract interface IEvaluator
{
public abstract boolean doEvaluate(ILoggingEvent paramILoggingEvent);
}

View File

@ -0,0 +1,155 @@
package ch.qos.logback.classic.boolex;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.classic.spi.LoggerContextVO;
import ch.qos.logback.classic.spi.ThrowableProxy;
import ch.qos.logback.core.CoreConstants;
import ch.qos.logback.core.boolex.JaninoEventEvaluatorBase;
import ch.qos.logback.core.boolex.Matcher;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.slf4j.Marker;
public class JaninoEventEvaluator
extends JaninoEventEvaluatorBase<ILoggingEvent>
{
public static final String IMPORT_LEVEL = "import ch.qos.logback.classic.Level;\r\n";
public static final List<String> DEFAULT_PARAM_NAME_LIST = new ArrayList();
public static final List<Class> DEFAULT_PARAM_TYPE_LIST = new ArrayList();
static {
DEFAULT_PARAM_NAME_LIST.add("DEBUG");
DEFAULT_PARAM_NAME_LIST.add("INFO");
DEFAULT_PARAM_NAME_LIST.add("WARN");
DEFAULT_PARAM_NAME_LIST.add("ERROR");
DEFAULT_PARAM_NAME_LIST.add("event");
DEFAULT_PARAM_NAME_LIST.add("message");
DEFAULT_PARAM_NAME_LIST.add("formattedMessage");
DEFAULT_PARAM_NAME_LIST.add("logger");
DEFAULT_PARAM_NAME_LIST.add("loggerContext");
DEFAULT_PARAM_NAME_LIST.add("level");
DEFAULT_PARAM_NAME_LIST.add("timeStamp");
DEFAULT_PARAM_NAME_LIST.add("marker");
DEFAULT_PARAM_NAME_LIST.add("mdc");
DEFAULT_PARAM_NAME_LIST.add("throwableProxy");
DEFAULT_PARAM_NAME_LIST.add("throwable");
DEFAULT_PARAM_TYPE_LIST.add(Integer.TYPE);
DEFAULT_PARAM_TYPE_LIST.add(Integer.TYPE);
DEFAULT_PARAM_TYPE_LIST.add(Integer.TYPE);
DEFAULT_PARAM_TYPE_LIST.add(Integer.TYPE);
DEFAULT_PARAM_TYPE_LIST.add(ILoggingEvent.class);
DEFAULT_PARAM_TYPE_LIST.add(String.class);
DEFAULT_PARAM_TYPE_LIST.add(String.class);
DEFAULT_PARAM_TYPE_LIST.add(String.class);
DEFAULT_PARAM_TYPE_LIST.add(LoggerContextVO.class);
DEFAULT_PARAM_TYPE_LIST.add(Integer.TYPE);
DEFAULT_PARAM_TYPE_LIST.add(Long.TYPE);
DEFAULT_PARAM_TYPE_LIST.add(Marker.class);
DEFAULT_PARAM_TYPE_LIST.add(Map.class);
DEFAULT_PARAM_TYPE_LIST.add(IThrowableProxy.class);
DEFAULT_PARAM_TYPE_LIST.add(Throwable.class);
}
protected String getDecoratedExpression() {
String expression = getExpression();
if (!expression.contains("return")) {
expression = "return " + expression + ";";
addInfo("Adding [return] prefix and a semicolon suffix. Expression becomes [" + expression + "]");
addInfo("See also http://logback.qos.ch/codes.html#block");
}
return "import ch.qos.logback.classic.Level;\r\n" + expression;
}
protected String[] getParameterNames() {
List<String> fullNameList = new ArrayList();
fullNameList.addAll(DEFAULT_PARAM_NAME_LIST);
for (int i = 0; i < matcherList.size(); i++) {
Matcher m = (Matcher)matcherList.get(i);
fullNameList.add(m.getName());
}
return (String[])fullNameList.toArray(CoreConstants.EMPTY_STRING_ARRAY);
}
protected Class[] getParameterTypes() {
List<Class> fullTypeList = new ArrayList();
fullTypeList.addAll(DEFAULT_PARAM_TYPE_LIST);
for (int i = 0; i < matcherList.size(); i++) {
fullTypeList.add(Matcher.class);
}
return (Class[])fullTypeList.toArray(CoreConstants.EMPTY_CLASS_ARRAY);
}
protected Object[] getParameterValues(ILoggingEvent loggingEvent) {
int matcherListSize = matcherList.size();
int i = 0;
Object[] values = new Object[DEFAULT_PARAM_NAME_LIST.size() + matcherListSize];
values[(i++)] = Level.DEBUG_INTEGER;
values[(i++)] = Level.INFO_INTEGER;
values[(i++)] = Level.WARN_INTEGER;
values[(i++)] = Level.ERROR_INTEGER;
values[(i++)] = loggingEvent;
values[(i++)] = loggingEvent.getMessage();
values[(i++)] = loggingEvent.getFormattedMessage();
values[(i++)] = loggingEvent.getLoggerName();
values[(i++)] = loggingEvent.getLoggerContextVO();
values[(i++)] = loggingEvent.getLevel().toInteger();
values[(i++)] = Long.valueOf(loggingEvent.getTimeStamp());
values[(i++)] = loggingEvent.getMarker();
values[(i++)] = loggingEvent.getMDCPropertyMap();
IThrowableProxy iThrowableProxy = loggingEvent.getThrowableProxy();
if (iThrowableProxy != null) {
values[(i++)] = iThrowableProxy;
if ((iThrowableProxy instanceof ThrowableProxy)) {
values[(i++)] = ((ThrowableProxy)iThrowableProxy).getThrowable();
} else {
values[(i++)] = null;
}
} else {
values[(i++)] = null;
values[(i++)] = null;
}
for (int j = 0; j < matcherListSize; j++) {
values[(i++)] = ((Matcher)matcherList.get(j));
}
return values;
}
public JaninoEventEvaluator() {}
}

View File

@ -0,0 +1,38 @@
package ch.qos.logback.classic.boolex;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.boolex.EvaluationException;
import ch.qos.logback.core.boolex.EventEvaluatorBase;
public class OnErrorEvaluator
extends EventEvaluatorBase<ILoggingEvent>
{
public OnErrorEvaluator() {}
public boolean evaluate(ILoggingEvent event)
throws NullPointerException, EvaluationException
{
return getLevellevelInt >= 40000;
}
}

View File

@ -0,0 +1,58 @@
package ch.qos.logback.classic.boolex;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.boolex.EvaluationException;
import ch.qos.logback.core.boolex.EventEvaluatorBase;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Marker;
public class OnMarkerEvaluator
extends EventEvaluatorBase<ILoggingEvent>
{
public OnMarkerEvaluator() {}
List<String> markerList = new ArrayList();
public void addMarker(String markerStr) {
markerList.add(markerStr);
}
public boolean evaluate(ILoggingEvent event)
throws NullPointerException, EvaluationException
{
Marker eventsMarker = event.getMarker();
if (eventsMarker == null) {
return false;
}
for (String markerStr : markerList) {
if (eventsMarker.contains(markerStr)) {
return true;
}
}
return false;
}
}

View File

@ -0,0 +1,314 @@
package ch.qos.logback.classic.db;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.db.names.DBNameResolver;
import ch.qos.logback.classic.db.names.DefaultDBNameResolver;
import ch.qos.logback.classic.spi.CallerData;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.classic.spi.LoggerContextVO;
import ch.qos.logback.classic.spi.StackTraceElementProxy;
import ch.qos.logback.classic.spi.ThrowableProxyUtil;
import ch.qos.logback.core.db.DBAppenderBase;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class DBAppender
extends DBAppenderBase<ILoggingEvent>
{
protected String insertPropertiesSQL;
protected String insertExceptionSQL;
protected String insertSQL;
protected static final Method GET_GENERATED_KEYS_METHOD;
private DBNameResolver dbNameResolver;
static final int TIMESTMP_INDEX = 1;
static final int FORMATTED_MESSAGE_INDEX = 2;
static final int LOGGER_NAME_INDEX = 3;
static final int LEVEL_STRING_INDEX = 4;
static final int THREAD_NAME_INDEX = 5;
static final int REFERENCE_FLAG_INDEX = 6;
static final int ARG0_INDEX = 7;
static final int ARG1_INDEX = 8;
static final int ARG2_INDEX = 9;
static final int ARG3_INDEX = 10;
static final int CALLER_FILENAME_INDEX = 11;
static final int CALLER_CLASS_INDEX = 12;
static final int CALLER_METHOD_INDEX = 13;
static final int CALLER_LINE_INDEX = 14;
static final int EVENT_ID_INDEX = 15;
static final StackTraceElement EMPTY_CALLER_DATA = ;
static
{
Method getGeneratedKeysMethod;
try
{
getGeneratedKeysMethod = PreparedStatement.class.getMethod("getGeneratedKeys", (Class[])null);
}
catch (Exception ex) {
getGeneratedKeysMethod = null;
}
GET_GENERATED_KEYS_METHOD = getGeneratedKeysMethod;
}
public void setDbNameResolver(DBNameResolver dbNameResolver) {
this.dbNameResolver = dbNameResolver;
}
public void start()
{
if (dbNameResolver == null)
dbNameResolver = new DefaultDBNameResolver();
insertExceptionSQL = SQLBuilder.buildInsertExceptionSQL(dbNameResolver);
insertPropertiesSQL = SQLBuilder.buildInsertPropertiesSQL(dbNameResolver);
insertSQL = SQLBuilder.buildInsertSQL(dbNameResolver);
super.start();
}
protected void subAppend(ILoggingEvent event, Connection connection, PreparedStatement insertStatement)
throws Throwable
{
bindLoggingEventWithInsertStatement(insertStatement, event);
bindLoggingEventArgumentsWithPreparedStatement(insertStatement, event.getArgumentArray());
bindCallerDataWithPreparedStatement(insertStatement, event.getCallerData());
int updateCount = insertStatement.executeUpdate();
if (updateCount != 1) {
addWarn("Failed to insert loggingEvent");
}
}
protected void secondarySubAppend(ILoggingEvent event, Connection connection, long eventId) throws Throwable
{
Map<String, String> mergedMap = mergePropertyMaps(event);
insertProperties(mergedMap, connection, eventId);
if (event.getThrowableProxy() != null) {
insertThrowable(event.getThrowableProxy(), connection, eventId);
}
}
void bindLoggingEventWithInsertStatement(PreparedStatement stmt, ILoggingEvent event) throws SQLException
{
stmt.setLong(1, event.getTimeStamp());
stmt.setString(2, event.getFormattedMessage());
stmt.setString(3, event.getLoggerName());
stmt.setString(4, event.getLevel().toString());
stmt.setString(5, event.getThreadName());
stmt.setShort(6, DBHelper.computeReferenceMask(event));
}
void bindLoggingEventArgumentsWithPreparedStatement(PreparedStatement stmt, Object[] argArray)
throws SQLException
{
int arrayLen = argArray != null ? argArray.length : 0;
for (int i = 0; (i < arrayLen) && (i < 4); i++) {
stmt.setString(7 + i, asStringTruncatedTo254(argArray[i]));
}
if (arrayLen < 4) {
for (int i = arrayLen; i < 4; i++) {
stmt.setString(7 + i, null);
}
}
}
String asStringTruncatedTo254(Object o) {
String s = null;
if (o != null) {
s = o.toString();
}
if (s == null) {
return null;
}
if (s.length() <= 254) {
return s;
}
return s.substring(0, 254);
}
void bindCallerDataWithPreparedStatement(PreparedStatement stmt, StackTraceElement[] callerDataArray)
throws SQLException
{
StackTraceElement caller = extractFirstCaller(callerDataArray);
stmt.setString(11, caller.getFileName());
stmt.setString(12, caller.getClassName());
stmt.setString(13, caller.getMethodName());
stmt.setString(14, Integer.toString(caller.getLineNumber()));
}
private StackTraceElement extractFirstCaller(StackTraceElement[] callerDataArray) {
StackTraceElement caller = EMPTY_CALLER_DATA;
if (hasAtLeastOneNonNullElement(callerDataArray))
caller = callerDataArray[0];
return caller;
}
private boolean hasAtLeastOneNonNullElement(StackTraceElement[] callerDataArray) {
return (callerDataArray != null) && (callerDataArray.length > 0) && (callerDataArray[0] != null);
}
Map<String, String> mergePropertyMaps(ILoggingEvent event) {
Map<String, String> mergedMap = new HashMap();
Map<String, String> loggerContextMap = event.getLoggerContextVO().getPropertyMap();
Map<String, String> mdcMap = event.getMDCPropertyMap();
if (loggerContextMap != null) {
mergedMap.putAll(loggerContextMap);
}
if (mdcMap != null) {
mergedMap.putAll(mdcMap);
}
return mergedMap;
}
protected Method getGeneratedKeysMethod()
{
return GET_GENERATED_KEYS_METHOD;
}
protected String getInsertSQL()
{
return insertSQL;
}
protected void insertProperties(Map<String, String> mergedMap, Connection connection, long eventId) throws SQLException
{
Set<String> propertiesKeys = mergedMap.keySet();
if (propertiesKeys.size() > 0) {
PreparedStatement insertPropertiesStatement = null;
try {
insertPropertiesStatement = connection.prepareStatement(insertPropertiesSQL);
for (String key : propertiesKeys) {
String value = (String)mergedMap.get(key);
insertPropertiesStatement.setLong(1, eventId);
insertPropertiesStatement.setString(2, key);
insertPropertiesStatement.setString(3, value);
if (cnxSupportsBatchUpdates) {
insertPropertiesStatement.addBatch();
} else {
insertPropertiesStatement.execute();
}
}
if (cnxSupportsBatchUpdates) {
insertPropertiesStatement.executeBatch();
}
} finally {
ch.qos.logback.core.db.DBHelper.closeStatement(insertPropertiesStatement);
}
}
}
void updateExceptionStatement(PreparedStatement exceptionStatement, String txt, short i, long eventId)
throws SQLException
{
exceptionStatement.setLong(1, eventId);
exceptionStatement.setShort(2, i);
exceptionStatement.setString(3, txt);
if (cnxSupportsBatchUpdates) {
exceptionStatement.addBatch();
} else {
exceptionStatement.execute();
}
}
short buildExceptionStatement(IThrowableProxy tp, short baseIndex, PreparedStatement insertExceptionStatement, long eventId)
throws SQLException
{
StringBuilder buf = new StringBuilder();
ThrowableProxyUtil.subjoinFirstLine(buf, tp);
baseIndex = (short)(baseIndex + 1);updateExceptionStatement(insertExceptionStatement, buf.toString(), baseIndex, eventId);
int commonFrames = tp.getCommonFrames();
StackTraceElementProxy[] stepArray = tp.getStackTraceElementProxyArray();
for (int i = 0; i < stepArray.length - commonFrames; i++) {
StringBuilder sb = new StringBuilder();
sb.append('\t');
ThrowableProxyUtil.subjoinSTEP(sb, stepArray[i]);
baseIndex = (short)(baseIndex + 1);updateExceptionStatement(insertExceptionStatement, sb.toString(), baseIndex, eventId);
}
if (commonFrames > 0) {
StringBuilder sb = new StringBuilder();
sb.append('\t').append("... ").append(commonFrames).append(" common frames omitted");
baseIndex = (short)(baseIndex + 1);updateExceptionStatement(insertExceptionStatement, sb.toString(), baseIndex, eventId);
}
return baseIndex;
}
protected void insertThrowable(IThrowableProxy tp, Connection connection, long eventId)
throws SQLException
{
PreparedStatement exceptionStatement = null;
try {
exceptionStatement = connection.prepareStatement(insertExceptionSQL);
short baseIndex = 0;
while (tp != null) {
baseIndex = buildExceptionStatement(tp, baseIndex, exceptionStatement, eventId);
tp = tp.getCause();
}
if (cnxSupportsBatchUpdates) {
exceptionStatement.executeBatch();
}
} finally {
ch.qos.logback.core.db.DBHelper.closeStatement(exceptionStatement);
}
}
public DBAppender() {}
}

View File

@ -0,0 +1,47 @@
package ch.qos.logback.classic.db;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.LoggerContextVO;
import java.util.Map;
import java.util.Set;
public class DBHelper
{
public static final short PROPERTIES_EXIST = 1;
public static final short EXCEPTION_EXISTS = 2;
public DBHelper() {}
public static short computeReferenceMask(ILoggingEvent event)
{
short mask = 0;
int mdcPropSize = 0;
if (event.getMDCPropertyMap() != null) {
mdcPropSize = event.getMDCPropertyMap().keySet().size();
}
int contextPropSize = 0;
if (event.getLoggerContextVO().getPropertyMap() != null) {
contextPropSize = event.getLoggerContextVO().getPropertyMap().size();
}
if ((mdcPropSize > 0) || (contextPropSize > 0)) {
mask = 1;
}
if (event.getThrowableProxy() != null) {
mask = (short)(mask | 0x2);
}
return mask;
}
}

View File

@ -0,0 +1,64 @@
package ch.qos.logback.classic.db;
import ch.qos.logback.classic.db.names.ColumnName;
import ch.qos.logback.classic.db.names.DBNameResolver;
import ch.qos.logback.classic.db.names.TableName;
public class SQLBuilder
{
public SQLBuilder() {}
static String buildInsertPropertiesSQL(DBNameResolver dbNameResolver)
{
StringBuilder sqlBuilder = new StringBuilder("INSERT INTO ");
sqlBuilder.append(dbNameResolver.getTableName(TableName.LOGGING_EVENT_PROPERTY)).append(" (");
sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.EVENT_ID)).append(", ");
sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.MAPPED_KEY)).append(", ");
sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.MAPPED_VALUE)).append(") ");
sqlBuilder.append("VALUES (?, ?, ?)");
return sqlBuilder.toString();
}
static String buildInsertExceptionSQL(DBNameResolver dbNameResolver) {
StringBuilder sqlBuilder = new StringBuilder("INSERT INTO ");
sqlBuilder.append(dbNameResolver.getTableName(TableName.LOGGING_EVENT_EXCEPTION)).append(" (");
sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.EVENT_ID)).append(", ");
sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.I)).append(", ");
sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.TRACE_LINE)).append(") ");
sqlBuilder.append("VALUES (?, ?, ?)");
return sqlBuilder.toString();
}
static String buildInsertSQL(DBNameResolver dbNameResolver) {
StringBuilder sqlBuilder = new StringBuilder("INSERT INTO ");
sqlBuilder.append(dbNameResolver.getTableName(TableName.LOGGING_EVENT)).append(" (");
sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.TIMESTMP)).append(", ");
sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.FORMATTED_MESSAGE)).append(", ");
sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.LOGGER_NAME)).append(", ");
sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.LEVEL_STRING)).append(", ");
sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.THREAD_NAME)).append(", ");
sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.REFERENCE_FLAG)).append(", ");
sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.ARG0)).append(", ");
sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.ARG1)).append(", ");
sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.ARG2)).append(", ");
sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.ARG3)).append(", ");
sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.CALLER_FILENAME)).append(", ");
sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.CALLER_CLASS)).append(", ");
sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.CALLER_METHOD)).append(", ");
sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.CALLER_LINE)).append(") ");
sqlBuilder.append("VALUES (?, ?, ? ,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
return sqlBuilder.toString();
}
}

View File

@ -0,0 +1,8 @@
package ch.qos.logback.classic.db.names;
public enum ColumnName
{
EVENT_ID, TIMESTMP, FORMATTED_MESSAGE, LOGGER_NAME, LEVEL_STRING, THREAD_NAME, REFERENCE_FLAG, ARG0, ARG1, ARG2, ARG3, CALLER_FILENAME, CALLER_CLASS, CALLER_METHOD, CALLER_LINE, MAPPED_KEY, MAPPED_VALUE, I, TRACE_LINE;
private ColumnName() {}
}

View File

@ -0,0 +1,8 @@
package ch.qos.logback.classic.db.names;
public abstract interface DBNameResolver
{
public abstract <N extends Enum<?>> String getTableName(N paramN);
public abstract <N extends Enum<?>> String getColumnName(N paramN);
}

View File

@ -0,0 +1,33 @@
package ch.qos.logback.classic.db.names;
public class DefaultDBNameResolver
implements DBNameResolver
{
public DefaultDBNameResolver() {}
public <N extends Enum<?>> String getTableName(N tableName)
{
return tableName.toString().toLowerCase();
}
public <N extends Enum<?>> String getColumnName(N columnName) {
return columnName.toString().toLowerCase();
}
}

View File

@ -0,0 +1,55 @@
package ch.qos.logback.classic.db.names;
public class SimpleDBNameResolver
implements DBNameResolver
{
public SimpleDBNameResolver() {}
private String tableNamePrefix = "";
private String tableNameSuffix = "";
private String columnNamePrefix = "";
private String columnNameSuffix = "";
public <N extends Enum<?>> String getTableName(N tableName) {
return tableNamePrefix + tableName.name().toLowerCase() + tableNameSuffix;
}
public <N extends Enum<?>> String getColumnName(N columnName) {
return columnNamePrefix + columnName.name().toLowerCase() + columnNameSuffix;
}
public void setTableNamePrefix(String tableNamePrefix) {
this.tableNamePrefix = (tableNamePrefix != null ? tableNamePrefix : "");
}
public void setTableNameSuffix(String tableNameSuffix) {
this.tableNameSuffix = (tableNameSuffix != null ? tableNameSuffix : "");
}
public void setColumnNamePrefix(String columnNamePrefix) {
this.columnNamePrefix = (columnNamePrefix != null ? columnNamePrefix : "");
}
public void setColumnNameSuffix(String columnNameSuffix) {
this.columnNameSuffix = (columnNameSuffix != null ? columnNameSuffix : "");
}
}

View File

@ -0,0 +1,8 @@
package ch.qos.logback.classic.db.names;
public enum TableName
{
LOGGING_EVENT, LOGGING_EVENT_PROPERTY, LOGGING_EVENT_EXCEPTION;
private TableName() {}
}

View File

@ -0,0 +1,32 @@
package ch.qos.logback.classic.encoder;
import ch.qos.logback.classic.PatternLayout;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.pattern.PatternLayoutEncoderBase;
public class PatternLayoutEncoder
extends PatternLayoutEncoderBase<ILoggingEvent>
{
public PatternLayoutEncoder() {}
public void start()
{
PatternLayout patternLayout = new PatternLayout();
patternLayout.setContext(context);
patternLayout.setPattern(getPattern());
patternLayout.setOutputPatternAsHeader(outputPatternAsHeader);
patternLayout.start();
layout = patternLayout;
super.start();
}
}

View File

@ -0,0 +1,57 @@
package ch.qos.logback.classic.filter;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.filter.AbstractMatcherFilter;
import ch.qos.logback.core.spi.FilterReply;
public class LevelFilter
extends AbstractMatcherFilter<ILoggingEvent>
{
Level level;
public LevelFilter() {}
public FilterReply decide(ILoggingEvent event)
{
if (!isStarted()) {
return FilterReply.NEUTRAL;
}
if (event.getLevel().equals(level)) {
return onMatch;
}
return onMismatch;
}
public void setLevel(Level level)
{
this.level = level;
}
public void start() {
if (level != null) {
super.start();
}
}
}

View File

@ -0,0 +1,61 @@
package ch.qos.logback.classic.filter;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;
public class ThresholdFilter
extends Filter<ILoggingEvent>
{
Level level;
public ThresholdFilter() {}
public FilterReply decide(ILoggingEvent event)
{
if (!isStarted()) {
return FilterReply.NEUTRAL;
}
if (event.getLevel().isGreaterOrEqual(level)) {
return FilterReply.NEUTRAL;
}
return FilterReply.DENY;
}
public void setLevel(String level)
{
this.level = Level.toLevel(level);
}
public void start() {
if (level != null) {
super.start();
}
}
}

View File

@ -0,0 +1,72 @@
package ch.qos.logback.classic.gaffer;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.spi.AppenderAttachable;
import groovy.lang.Closure;
import java.util.List;
import java.util.Map;
import org.codehaus.groovy.runtime.GeneratedClosure;
import org.codehaus.groovy.runtime.ScriptBytecodeAdapter;
import org.codehaus.groovy.runtime.callsite.CallSite;
import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation;
public class AppenderDelegate
extends ComponentDelegate
{
private Map<String, Appender<?>> appendersByName;
public AppenderDelegate(Appender appender)
{
super(appender);Map localMap = ScriptBytecodeAdapter.createMap(new Object[0]);appendersByName = localMap;
}
class _closure1 extends Closure implements GeneratedClosure { public _closure1(Object _thisObject) { super(_thisObject); }
public Object doCall(Object it) { CallSite[] arrayOfCallSite = $getCallSiteArray();return ScriptBytecodeAdapter.createMap(new Object[] { arrayOfCallSite[0].callGetProperty(it), it });return null;
}
public Object doCall()
{
CallSite[] arrayOfCallSite = $getCallSiteArray();
return doCall(null);
return null;
}
}
public AppenderDelegate(Appender appender, List<Appender<?>> appenders)
{
super(appender);Map localMap = ScriptBytecodeAdapter.createMap(new Object[0]);appendersByName = localMap;
Object localObject = arrayOfCallSite[0].call(appenders, new _closure1(this));appendersByName = ((Map)ScriptBytecodeAdapter.castToType(localObject, Map.class));
}
public String getLabel() {
CallSite[] arrayOfCallSite = $getCallSiteArray();return "appender";return null;
}
public void appenderRef(String name) {
CallSite[] arrayOfCallSite = $getCallSiteArray(); if ((!DefaultTypeTransformation.booleanUnbox(arrayOfCallSite[1].call(AppenderAttachable.class, arrayOfCallSite[2].callGetProperty(arrayOfCallSite[3].callGroovyObjectGetProperty(this)))) ? 1 : 0) != 0) {
Object errorMessage = arrayOfCallSite[4].call(arrayOfCallSite[5].call(arrayOfCallSite[6].call(arrayOfCallSite[7].callGetProperty(arrayOfCallSite[8].callGetProperty(arrayOfCallSite[9].callGroovyObjectGetProperty(this))), " does not implement "), arrayOfCallSite[10].callGetProperty(AppenderAttachable.class)), ".");
throw ((Throwable)arrayOfCallSite[11].callConstructor(IllegalArgumentException.class, errorMessage));
}
arrayOfCallSite[12].call(arrayOfCallSite[13].callGroovyObjectGetProperty(this), arrayOfCallSite[14].call(appendersByName, name));
}
public Map<String, Appender<?>> getAppendersByName()
{
return appendersByName;
}
public void setAppendersByName(Map<String, Appender<?>> paramMap)
{
appendersByName = paramMap;
}
}

View File

@ -0,0 +1,204 @@
package ch.qos.logback.classic.gaffer;
import ch.qos.logback.core.joran.spi.NoAutoStartUtil;
import ch.qos.logback.core.spi.ContextAware;
import ch.qos.logback.core.spi.ContextAwareBase;
import ch.qos.logback.core.spi.LifeCycle;
import groovy.lang.Closure;
import groovy.lang.GroovyObject;
import groovy.lang.MetaClass;
import java.util.Iterator;
import java.util.List;
import org.codehaus.groovy.runtime.BytecodeInterface8;
import org.codehaus.groovy.runtime.GStringImpl;
import org.codehaus.groovy.runtime.ScriptBytecodeAdapter;
import org.codehaus.groovy.runtime.callsite.CallSite;
import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation;
import org.codehaus.groovy.runtime.typehandling.ShortTypeHandling;
public class ComponentDelegate
extends ContextAwareBase implements GroovyObject
{
private final Object component;
private final List fieldsToCascade;
public ComponentDelegate(Object arg1)
{
Object component;
CallSite[] arrayOfCallSite = $getCallSiteArray();List localList = ScriptBytecodeAdapter.createList(new Object[0]);fieldsToCascade = localList;MetaClass localMetaClass = $getStaticMetaClass();metaClass = localMetaClass;
Object localObject1 = component;this.component = localObject1;
}
public String getLabel() { CallSite[] arrayOfCallSite = $getCallSiteArray();return "component";return null; }
public String getLabelFistLetterInUpperCase() { CallSite[] arrayOfCallSite = $getCallSiteArray(); if ((__$stMC) || (BytecodeInterface8.disabledStandardMetaClass())) return (String)ShortTypeHandling.castToString(arrayOfCallSite[0].call(arrayOfCallSite[1].call(arrayOfCallSite[2].call(arrayOfCallSite[3].callCurrent(this), Integer.valueOf(0))), arrayOfCallSite[4].call(arrayOfCallSite[5].callCurrent(this), Integer.valueOf(1)))); else return (String)ShortTypeHandling.castToString(arrayOfCallSite[6].call(arrayOfCallSite[7].call(arrayOfCallSite[8].call(getLabel(), Integer.valueOf(0))), arrayOfCallSite[9].call(getLabel(), Integer.valueOf(1)))); return null;
}
public void methodMissing(String name, Object args) { CallSite[] arrayOfCallSite = $getCallSiteArray();NestingType nestingType = (NestingType)ShortTypeHandling.castToEnum(arrayOfCallSite[10].call(PropertyUtil.class, component, name), NestingType.class);
if (ScriptBytecodeAdapter.compareEqual(nestingType, arrayOfCallSite[11].callGetProperty(NestingType.class))) {
arrayOfCallSite[12].callCurrent(this, new GStringImpl(new Object[] { arrayOfCallSite[13].callCurrent(this), arrayOfCallSite[14].callCurrent(this), arrayOfCallSite[15].callGetProperty(arrayOfCallSite[16].call(component)), name }, new String[] { "", " ", " of type [", "] has no appplicable [", "] property " }));
return;
}
String subComponentName = null;
Class clazz = null;
Closure closure = null;
Object localObject1 = arrayOfCallSite[17].callCurrent(this, args);subComponentName = (String)ShortTypeHandling.castToString(arrayOfCallSite[18].call(localObject1, Integer.valueOf(0)));clazz = (Class)ShortTypeHandling.castToClass(arrayOfCallSite[19].call(localObject1, Integer.valueOf(1)));closure = (Closure)ScriptBytecodeAdapter.castToType(arrayOfCallSite[20].call(localObject1, Integer.valueOf(2)), Closure.class);
if ((!BytecodeInterface8.isOrigZ()) || (__$stMC) || (BytecodeInterface8.disabledStandardMetaClass())) { if (ScriptBytecodeAdapter.compareNotEqual(clazz, null)) {
Object subComponent = arrayOfCallSite[21].call(clazz);
String str1; if (((DefaultTypeTransformation.booleanUnbox(subComponentName)) && (DefaultTypeTransformation.booleanUnbox(arrayOfCallSite[22].call(subComponent, name))) ? 1 : 0) != 0) {
str1 = subComponentName;ScriptBytecodeAdapter.setProperty(str1, null, subComponent, "name"); }
Object localObject2;
if ((subComponent instanceof ContextAware)) {
localObject2 = arrayOfCallSite[23].callGroovyObjectGetProperty(this);ScriptBytecodeAdapter.setProperty(localObject2, null, subComponent, "context");
}
if (DefaultTypeTransformation.booleanUnbox(closure)) {
ComponentDelegate subDelegate = (ComponentDelegate)ScriptBytecodeAdapter.castToType(arrayOfCallSite[24].callConstructor(ComponentDelegate.class, subComponent), ComponentDelegate.class);
arrayOfCallSite[25].callCurrent(this, subDelegate);
Object localObject3 = arrayOfCallSite[26].callGroovyObjectGetProperty(this);ScriptBytecodeAdapter.setGroovyObjectProperty(localObject3, ComponentDelegate.class, subDelegate, "context");
arrayOfCallSite[27].callCurrent(this, subComponent);
ComponentDelegate localComponentDelegate1 = subDelegate;ScriptBytecodeAdapter.setGroovyObjectProperty(localComponentDelegate1, ComponentDelegate.class, closure, "delegate");
Object localObject4 = arrayOfCallSite[28].callGetProperty(Closure.class);ScriptBytecodeAdapter.setGroovyObjectProperty(localObject4, ComponentDelegate.class, closure, "resolveStrategy");
arrayOfCallSite[29].call(closure);
}
if ((((subComponent instanceof LifeCycle)) && (DefaultTypeTransformation.booleanUnbox(arrayOfCallSite[30].call(NoAutoStartUtil.class, subComponent))) ? 1 : 0) != 0) {
arrayOfCallSite[31].call(subComponent);
}
arrayOfCallSite[32].call(PropertyUtil.class, nestingType, component, subComponent, name);
} else {
arrayOfCallSite[33].callCurrent(this, new GStringImpl(new Object[] { name, arrayOfCallSite[34].callCurrent(this), arrayOfCallSite[35].callCurrent(this), arrayOfCallSite[36].callGetProperty(arrayOfCallSite[37].call(component)) }, new String[] { "No 'class' argument specified for [", "] in ", " ", " of type [", "]" }));
}
}
else if (ScriptBytecodeAdapter.compareNotEqual(clazz, null)) {
Object subComponent = arrayOfCallSite[38].call(clazz);
String str2; if (((DefaultTypeTransformation.booleanUnbox(subComponentName)) && (DefaultTypeTransformation.booleanUnbox(arrayOfCallSite[39].call(subComponent, name))) ? 1 : 0) != 0) {
str2 = subComponentName;ScriptBytecodeAdapter.setProperty(str2, null, subComponent, "name"); }
Object localObject5;
if ((subComponent instanceof ContextAware)) {
localObject5 = arrayOfCallSite[40].callGroovyObjectGetProperty(this);ScriptBytecodeAdapter.setProperty(localObject5, null, subComponent, "context");
}
if (DefaultTypeTransformation.booleanUnbox(closure)) {
ComponentDelegate subDelegate = (ComponentDelegate)ScriptBytecodeAdapter.castToType(arrayOfCallSite[41].callConstructor(ComponentDelegate.class, subComponent), ComponentDelegate.class);
arrayOfCallSite[42].callCurrent(this, subDelegate);
Object localObject6 = arrayOfCallSite[43].callGroovyObjectGetProperty(this);ScriptBytecodeAdapter.setGroovyObjectProperty(localObject6, ComponentDelegate.class, subDelegate, "context");
arrayOfCallSite[44].callCurrent(this, subComponent);
ComponentDelegate localComponentDelegate2 = subDelegate;ScriptBytecodeAdapter.setGroovyObjectProperty(localComponentDelegate2, ComponentDelegate.class, closure, "delegate");
Object localObject7 = arrayOfCallSite[45].callGetProperty(Closure.class);ScriptBytecodeAdapter.setGroovyObjectProperty(localObject7, ComponentDelegate.class, closure, "resolveStrategy");
arrayOfCallSite[46].call(closure);
}
if ((((subComponent instanceof LifeCycle)) && (DefaultTypeTransformation.booleanUnbox(arrayOfCallSite[47].call(NoAutoStartUtil.class, subComponent))) ? 1 : 0) != 0) {
arrayOfCallSite[48].call(subComponent);
}
arrayOfCallSite[49].call(PropertyUtil.class, nestingType, component, subComponent, name);
} else {
arrayOfCallSite[50].callCurrent(this, new GStringImpl(new Object[] { name, getLabel(), getComponentName(), arrayOfCallSite[51].callGetProperty(arrayOfCallSite[52].call(component)) }, new String[] { "No 'class' argument specified for [", "] in ", " ", " of type [", "]" }));
}
}
public void cascadeFields(ComponentDelegate subDelegate) {
CallSite[] arrayOfCallSite = $getCallSiteArray();String k = null; Object localObject; for (Iterator localIterator = (Iterator)ScriptBytecodeAdapter.castToType(arrayOfCallSite[53].call(fieldsToCascade), Iterator.class); localIterator.hasNext();
ScriptBytecodeAdapter.setProperty(localObject, null, arrayOfCallSite[54].callGroovyObjectGetProperty(subDelegate), (String)ShortTypeHandling.castToString(new GStringImpl(new Object[] { k }, new String[] { "", "" }))))
{
k = (String)ShortTypeHandling.castToString(localIterator.next());
localObject = ScriptBytecodeAdapter.getGroovyObjectProperty(ComponentDelegate.class, this, (String)ShortTypeHandling.castToString(new GStringImpl(new Object[] { k }, new String[] { "", "" })));
}
}
public void injectParent(Object subComponent) {
CallSite[] arrayOfCallSite = $getCallSiteArray(); Object localObject; if (DefaultTypeTransformation.booleanUnbox(arrayOfCallSite[55].call(subComponent, "parent"))) {
localObject = component;ScriptBytecodeAdapter.setProperty(localObject, null, subComponent, "parent");
}
}
public void propertyMissing(String name, Object value) {
CallSite[] arrayOfCallSite = $getCallSiteArray();NestingType nestingType = (NestingType)ShortTypeHandling.castToEnum(arrayOfCallSite[56].call(PropertyUtil.class, component, name), NestingType.class);
if (ScriptBytecodeAdapter.compareEqual(nestingType, arrayOfCallSite[57].callGetProperty(NestingType.class))) {
arrayOfCallSite[58].callCurrent(this, new GStringImpl(new Object[] { arrayOfCallSite[59].callCurrent(this), arrayOfCallSite[60].callCurrent(this), arrayOfCallSite[61].callGetProperty(arrayOfCallSite[62].call(component)), name }, new String[] { "", " ", " of type [", "] has no appplicable [", "] property " }));
return;
}
arrayOfCallSite[63].call(PropertyUtil.class, nestingType, component, value, name);
}
public Object analyzeArgs(Object... args)
{
CallSite[] arrayOfCallSite = $getCallSiteArray();String name = null;
Class clazz = null;
Closure closure = null;
if (ScriptBytecodeAdapter.compareGreaterThan(arrayOfCallSite[64].call(args), Integer.valueOf(3))) {
arrayOfCallSite[65].callCurrent(this, new GStringImpl(new Object[] { args }, new String[] { "At most 3 arguments allowed but you passed ", "" }));
return ScriptBytecodeAdapter.createList(new Object[] { name, clazz, closure });
}
if ((__$stMC) || (BytecodeInterface8.disabledStandardMetaClass())) { if ((arrayOfCallSite[66].call(args, Integer.valueOf(-1)) instanceof Closure)) {
Object localObject1 = arrayOfCallSite[67].call(args, Integer.valueOf(-1));closure = (Closure)ScriptBytecodeAdapter.castToType(localObject1, Closure.class); Object
tmp202_197 = arrayOfCallSite[68].call(args, arrayOfCallSite[69].call(args, Integer.valueOf(-1)));args = (Object[])ScriptBytecodeAdapter.castToType(tmp202_197, [Ljava.lang.Object.class);tmp202_197;
}
}
else if ((BytecodeInterface8.objectArrayGet(args, Integer.valueOf(-1).intValue()) instanceof Closure)) {
Object localObject2 = BytecodeInterface8.objectArrayGet(args, Integer.valueOf(-1).intValue());closure = (Closure)ScriptBytecodeAdapter.castToType(localObject2, Closure.class); Object
tmp287_282 = arrayOfCallSite[70].call(args, BytecodeInterface8.objectArrayGet(args, Integer.valueOf(-1).intValue()));args = (Object[])ScriptBytecodeAdapter.castToType(tmp287_282, [Ljava.lang.Object.class);tmp287_282; }
Object localObject3;
Object localObject4;
if ((!BytecodeInterface8.isOrigInt()) || (!BytecodeInterface8.isOrigZ()) || (__$stMC) || (BytecodeInterface8.disabledStandardMetaClass())) { if (ScriptBytecodeAdapter.compareEqual(arrayOfCallSite[71].call(args), Integer.valueOf(1))) {
localObject3 = arrayOfCallSite[72].callCurrent(this, arrayOfCallSite[73].call(args, Integer.valueOf(0)));clazz = (Class)ShortTypeHandling.castToClass(localObject3);
}
}
else if (ScriptBytecodeAdapter.compareEqual(arrayOfCallSite[74].call(args), Integer.valueOf(1))) {
localObject4 = arrayOfCallSite[75].callCurrent(this, BytecodeInterface8.objectArrayGet(args, 0));clazz = (Class)ShortTypeHandling.castToClass(localObject4); }
Object localObject6;
Object localObject8;
if ((!BytecodeInterface8.isOrigInt()) || (!BytecodeInterface8.isOrigZ()) || (__$stMC) || (BytecodeInterface8.disabledStandardMetaClass())) { if (ScriptBytecodeAdapter.compareEqual(arrayOfCallSite[76].call(args), Integer.valueOf(2))) {
Object localObject5 = arrayOfCallSite[77].callCurrent(this, arrayOfCallSite[78].call(args, Integer.valueOf(0)));name = (String)ShortTypeHandling.castToString(localObject5);
localObject6 = arrayOfCallSite[79].callCurrent(this, arrayOfCallSite[80].call(args, Integer.valueOf(1)));clazz = (Class)ShortTypeHandling.castToClass(localObject6);
}
}
else if (ScriptBytecodeAdapter.compareEqual(arrayOfCallSite[81].call(args), Integer.valueOf(2))) {
Object localObject7 = arrayOfCallSite[82].callCurrent(this, BytecodeInterface8.objectArrayGet(args, 0));name = (String)ShortTypeHandling.castToString(localObject7);
localObject8 = arrayOfCallSite[83].callCurrent(this, BytecodeInterface8.objectArrayGet(args, 1));clazz = (Class)ShortTypeHandling.castToClass(localObject8);
}
return ScriptBytecodeAdapter.createList(new Object[] { name, clazz, closure });return null;
}
public Class parseClassArgument(Object arg) {
CallSite[] arrayOfCallSite = $getCallSiteArray(); if ((arg instanceof Class)) {
return (Class)ShortTypeHandling.castToClass(arg);
} else if ((arg instanceof String)) {
return Class.forName((String)ShortTypeHandling.castToString(arg));
} else {
arrayOfCallSite[84].callCurrent(this, new GStringImpl(new Object[] { arrayOfCallSite[85].callGetProperty(arrayOfCallSite[86].call(arg)) }, new String[] { "Unexpected argument type ", "" }));
return (Class)ShortTypeHandling.castToClass(null); } return null;
}
public String parseNameArgument(Object arg)
{
CallSite[] arrayOfCallSite = $getCallSiteArray(); if ((arg instanceof String)) {
return (String)ShortTypeHandling.castToString(arg);
} else {
arrayOfCallSite[87].callCurrent(this, "With 2 or 3 arguments, the first argument must be the component name, i.e of type string");
return (String)ShortTypeHandling.castToString(null); } return null;
}
public String getComponentName()
{
CallSite[] arrayOfCallSite = $getCallSiteArray(); if (DefaultTypeTransformation.booleanUnbox(arrayOfCallSite[88].call(component, "name"))) {
return (String)ShortTypeHandling.castToString(new GStringImpl(new Object[] { arrayOfCallSite[89].callGetProperty(component) }, new String[] { "[", "]" }));
} else
return ""; return null;
}
public final Object getComponent()
{
return component;
}
public final List getFieldsToCascade()
{
return fieldsToCascade;
}
}

View File

@ -0,0 +1,8 @@
package ch.qos.logback.classic.gaffer;
import java.util.Map;
public abstract interface ConfigurationContributor
{
public abstract Map<String, String> getMappings();
}

View File

@ -0,0 +1,357 @@
package ch.qos.logback.classic.gaffer;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.jmx.JMXConfigurator;
import ch.qos.logback.classic.jmx.MBeanUtil;
import ch.qos.logback.classic.net.ReceiverBase;
import ch.qos.logback.classic.turbo.ReconfigureOnChangeFilter;
import ch.qos.logback.classic.turbo.TurboFilter;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.CoreConstants;
import ch.qos.logback.core.spi.ContextAware;
import ch.qos.logback.core.spi.ContextAwareBase;
import ch.qos.logback.core.spi.LifeCycle;
import ch.qos.logback.core.status.StatusListener;
import ch.qos.logback.core.util.CachingDateFormatter;
import ch.qos.logback.core.util.Duration;
import groovy.lang.Closure;
import groovy.lang.GroovyObject;
import groovy.lang.MetaClass;
import groovy.lang.Reference;
import java.lang.management.ManagementFactory;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import org.codehaus.groovy.runtime.BytecodeInterface8;
import org.codehaus.groovy.runtime.GStringImpl;
import org.codehaus.groovy.runtime.GeneratedClosure;
import org.codehaus.groovy.runtime.ScriptBytecodeAdapter;
import org.codehaus.groovy.runtime.callsite.CallSite;
import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation;
import org.codehaus.groovy.runtime.typehandling.ShortTypeHandling;
public class ConfigurationDelegate extends ContextAwareBase implements GroovyObject
{
private List<Appender> appenderList;
public ConfigurationDelegate()
{
ConfigurationDelegate this;
CallSite[] arrayOfCallSite = $getCallSiteArray();List localList = ScriptBytecodeAdapter.createList(new Object[0]);appenderList = localList;MetaClass localMetaClass = $getStaticMetaClass();metaClass = localMetaClass;
}
public Object getDeclaredOrigin() { CallSite[] arrayOfCallSite = $getCallSiteArray();return this;return null;
}
public void scan(String scanPeriodStr)
{
CallSite[] arrayOfCallSite = $getCallSiteArray();ReconfigureOnChangeFilter rocf = (ReconfigureOnChangeFilter)ScriptBytecodeAdapter.castToType(arrayOfCallSite[0].callConstructor(ReconfigureOnChangeFilter.class), ReconfigureOnChangeFilter.class);
arrayOfCallSite[1].call(rocf, arrayOfCallSite[2].callGroovyObjectGetProperty(this));
if (DefaultTypeTransformation.booleanUnbox(scanPeriodStr))
try {
try { Duration duration = (Duration)ScriptBytecodeAdapter.castToType(arrayOfCallSite[3].call(Duration.class, scanPeriodStr), Duration.class);
arrayOfCallSite[4].call(rocf, arrayOfCallSite[5].call(duration));
arrayOfCallSite[6].callCurrent(this, arrayOfCallSite[7].call("Setting ReconfigureOnChangeFilter scanning period to ", duration));
}
catch (NumberFormatException nfe) {
arrayOfCallSite[8].callCurrent(this, arrayOfCallSite[9].call(arrayOfCallSite[10].call("Error while converting [", arrayOfCallSite[11].callGroovyObjectGetProperty(this)), "] to long"), nfe);
}
} finally {}
arrayOfCallSite[12].call(rocf);
arrayOfCallSite[13].callCurrent(this, "Adding ReconfigureOnChangeFilter as a turbo filter");
arrayOfCallSite[14].call(arrayOfCallSite[15].callGroovyObjectGetProperty(this), rocf);
}
public void statusListener(Class listenerClass) {
CallSite[] arrayOfCallSite = $getCallSiteArray();StatusListener statusListener = (StatusListener)ScriptBytecodeAdapter.castToType(arrayOfCallSite[16].call(listenerClass), StatusListener.class);
arrayOfCallSite[17].call(arrayOfCallSite[18].callGetProperty(arrayOfCallSite[19].callGroovyObjectGetProperty(this)), statusListener);
if ((statusListener instanceof ContextAware)) {
arrayOfCallSite[20].call((ContextAware)ScriptBytecodeAdapter.castToType(statusListener, ContextAware.class), arrayOfCallSite[21].callGroovyObjectGetProperty(this));
}
if ((statusListener instanceof LifeCycle)) {
arrayOfCallSite[22].call((LifeCycle)ScriptBytecodeAdapter.castToType(statusListener, LifeCycle.class));
}
arrayOfCallSite[23].callCurrent(this, new GStringImpl(new Object[] { arrayOfCallSite[24].callGetProperty(listenerClass) }, new String[] { "Added status listener of type [", "]" }));
}
public void conversionRule(String conversionWord, Class converterClass) {
CallSite[] arrayOfCallSite = $getCallSiteArray();String converterClassName = (String)ShortTypeHandling.castToString(arrayOfCallSite[25].call(converterClass));
Map ruleRegistry = (Map)ScriptBytecodeAdapter.castToType(arrayOfCallSite[26].call(arrayOfCallSite[27].callGroovyObjectGetProperty(this), arrayOfCallSite[28].callGetProperty(CoreConstants.class)), Map.class);
if (ScriptBytecodeAdapter.compareEqual(ruleRegistry, null)) {
Object localObject = arrayOfCallSite[29].callConstructor(HashMap.class);ruleRegistry = (Map)ScriptBytecodeAdapter.castToType(localObject, Map.class);
arrayOfCallSite[30].call(arrayOfCallSite[31].callGroovyObjectGetProperty(this), arrayOfCallSite[32].callGetProperty(CoreConstants.class), ruleRegistry);
}
arrayOfCallSite[33].callCurrent(this, arrayOfCallSite[34].call(arrayOfCallSite[35].call(arrayOfCallSite[36].call(arrayOfCallSite[37].call("registering conversion word ", conversionWord), " with class ["), converterClassName), "]"));
arrayOfCallSite[38].call(ruleRegistry, conversionWord, converterClassName);
}
public void root(Level level) { CallSite[] arrayOfCallSite = $getCallSiteArray();root(level, ScriptBytecodeAdapter.createList(new Object[0]));null; }
public void root(Level level, List<String> appenderNames) { CallSite[] arrayOfCallSite = $getCallSiteArray(); if (ScriptBytecodeAdapter.compareEqual(level, null)) {
arrayOfCallSite[39].callCurrent(this, "Root logger cannot be set to level null");
} else
arrayOfCallSite[40].callCurrent(this, arrayOfCallSite[41].callGetProperty(org.slf4j.Logger.class), level, appenderNames);
}
public void logger(String name, Level level) {
CallSite[] arrayOfCallSite = $getCallSiteArray();logger(name, level, ScriptBytecodeAdapter.createList(new Object[0]), null);null;
}
class _logger_closure1 extends Closure implements GeneratedClosure {
public _logger_closure1(Object _thisObject, Reference aName) { super(_thisObject);
Reference localReference = aName;
this.aName = localReference;
}
public Object doCall(Object it) { CallSite[] arrayOfCallSite = $getCallSiteArray();return Boolean.valueOf(ScriptBytecodeAdapter.compareEqual(arrayOfCallSite[0].callGetProperty(it), aName.get()));return null;
}
public Object getaName()
{
CallSite[] arrayOfCallSite = $getCallSiteArray();
return aName.get();
return null;
}
}
public void logger(String name, Level level, List<String> appenderNames, Boolean additivity)
{
CallSite[] arrayOfCallSite = $getCallSiteArray(); Boolean localBoolean; if (DefaultTypeTransformation.booleanUnbox(name)) {
ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger)ScriptBytecodeAdapter.castToType(arrayOfCallSite[42].call((LoggerContext)ScriptBytecodeAdapter.castToType(arrayOfCallSite[43].callGroovyObjectGetProperty(this), LoggerContext.class), name), ch.qos.logback.classic.Logger.class);
arrayOfCallSite[44].callCurrent(this, arrayOfCallSite[45].call(new GStringImpl(new Object[] { name }, new String[] { "Setting level of logger [", "] to " }), level));
Level localLevel = level;ScriptBytecodeAdapter.setProperty(localLevel, null, logger, "level");
Reference aName = new Reference(null); for (Iterator localIterator = (Iterator)ScriptBytecodeAdapter.castToType(arrayOfCallSite[46].call(appenderNames), Iterator.class); localIterator.hasNext();) { ((Reference)aName).set(localIterator.next());
Appender appender = (Appender)ScriptBytecodeAdapter.castToType(arrayOfCallSite[47].call(appenderList, new _logger_closure1(this, aName)), Appender.class);
if (ScriptBytecodeAdapter.compareNotEqual(appender, null)) {
arrayOfCallSite[48].callCurrent(this, arrayOfCallSite[49].call(new GStringImpl(new Object[] { aName.get() }, new String[] { "Attaching appender named [", "] to " }), logger));
arrayOfCallSite[50].call(logger, appender);
} else {
arrayOfCallSite[51].callCurrent(this, new GStringImpl(new Object[] { aName.get() }, new String[] { "Failed to find appender named [", "]" }));
}
}
if (ScriptBytecodeAdapter.compareNotEqual(additivity, null)) {
localBoolean = additivity;ScriptBytecodeAdapter.setProperty(localBoolean, null, logger, "additive");
}
} else {
arrayOfCallSite[52].callCurrent(this, "No name attribute for logger");
}
}
public void appender(String name, Class clazz, Closure closure) {
CallSite[] arrayOfCallSite = $getCallSiteArray();arrayOfCallSite[53].callCurrent(this, arrayOfCallSite[54].call(arrayOfCallSite[55].call("About to instantiate appender of type [", arrayOfCallSite[56].callGetProperty(clazz)), "]"));
Appender appender = (Appender)ScriptBytecodeAdapter.castToType(arrayOfCallSite[57].call(clazz), Appender.class);
arrayOfCallSite[58].callCurrent(this, arrayOfCallSite[59].call(arrayOfCallSite[60].call("Naming appender as [", name), "]"));
String str = name;ScriptBytecodeAdapter.setProperty(str, null, appender, "name");
Object localObject1 = arrayOfCallSite[61].callGroovyObjectGetProperty(this);ScriptBytecodeAdapter.setProperty(localObject1, null, appender, "context");
arrayOfCallSite[62].call(appenderList, appender);
if (ScriptBytecodeAdapter.compareNotEqual(closure, null)) {
AppenderDelegate ad = (AppenderDelegate)ScriptBytecodeAdapter.castToType(arrayOfCallSite[63].callConstructor(AppenderDelegate.class, appender, appenderList), AppenderDelegate.class);
arrayOfCallSite[64].callCurrent(this, ad, appender);
Object localObject2 = arrayOfCallSite[65].callGroovyObjectGetProperty(this);ScriptBytecodeAdapter.setGroovyObjectProperty(localObject2, ConfigurationDelegate.class, ad, "context");
AppenderDelegate localAppenderDelegate1 = ad;ScriptBytecodeAdapter.setGroovyObjectProperty(localAppenderDelegate1, ConfigurationDelegate.class, closure, "delegate");
Object localObject3 = arrayOfCallSite[66].callGetProperty(Closure.class);ScriptBytecodeAdapter.setGroovyObjectProperty(localObject3, ConfigurationDelegate.class, closure, "resolveStrategy");
arrayOfCallSite[67].call(closure);
}
try {
try { arrayOfCallSite[68].call(appender);
} catch (RuntimeException e) {
arrayOfCallSite[69].callCurrent(this, arrayOfCallSite[70].call(arrayOfCallSite[71].call("Failed to start apppender named [", name), "]"), e);
}
} finally {}
}
public void receiver(String name, Class aClass, Closure closure) { CallSite[] arrayOfCallSite = $getCallSiteArray();arrayOfCallSite[72].callCurrent(this, arrayOfCallSite[73].call(arrayOfCallSite[74].call("About to instantiate receiver of type [", arrayOfCallSite[75].callGetProperty(arrayOfCallSite[76].callGroovyObjectGetProperty(this))), "]"));
ReceiverBase receiver = (ReceiverBase)ScriptBytecodeAdapter.castToType(arrayOfCallSite[77].call(aClass), ReceiverBase.class);
Object localObject1 = arrayOfCallSite[78].callGroovyObjectGetProperty(this);ScriptBytecodeAdapter.setProperty(localObject1, null, receiver, "context");
if (ScriptBytecodeAdapter.compareNotEqual(closure, null)) {
ComponentDelegate componentDelegate = (ComponentDelegate)ScriptBytecodeAdapter.castToType(arrayOfCallSite[79].callConstructor(ComponentDelegate.class, receiver), ComponentDelegate.class);
Object localObject2 = arrayOfCallSite[80].callGroovyObjectGetProperty(this);ScriptBytecodeAdapter.setGroovyObjectProperty(localObject2, ConfigurationDelegate.class, componentDelegate, "context");
ComponentDelegate localComponentDelegate1 = componentDelegate;ScriptBytecodeAdapter.setGroovyObjectProperty(localComponentDelegate1, ConfigurationDelegate.class, closure, "delegate");
Object localObject3 = arrayOfCallSite[81].callGetProperty(Closure.class);ScriptBytecodeAdapter.setGroovyObjectProperty(localObject3, ConfigurationDelegate.class, closure, "resolveStrategy");
arrayOfCallSite[82].call(closure);
}
try {
try { arrayOfCallSite[83].call(receiver);
} catch (RuntimeException e) {
arrayOfCallSite[84].callCurrent(this, arrayOfCallSite[85].call(arrayOfCallSite[86].call("Failed to start receiver of type [", arrayOfCallSite[87].call(aClass)), "]"), e);
}
} finally {}
}
private void copyContributions(AppenderDelegate appenderDelegate, Appender appender) { Reference appenderDelegate = new Reference(appenderDelegate);Reference appender = new Reference(appender);CallSite[] arrayOfCallSite = $getCallSiteArray(); if (((Appender)appender.get() instanceof ConfigurationContributor)) {
ConfigurationContributor cc = (ConfigurationContributor)ScriptBytecodeAdapter.castToType((Appender)appender.get(), ConfigurationContributor.class);
arrayOfCallSite[88].call(arrayOfCallSite[89].call(cc), new _copyContributions_closure2(this, appenderDelegate, appender)); } }
class _copyContributions_closure2 extends Closure implements GeneratedClosure { public _copyContributions_closure2(Object _thisObject, Reference appenderDelegate, Reference appender) { super(_thisObject);
Reference localReference1 = appenderDelegate;
this.appenderDelegate = localReference1;
Reference localReference2 = appender;
this.appender = localReference2; } public Object doCall(Object oldName, Object newName) { CallSite[] arrayOfCallSite = $getCallSiteArray();Closure localClosure = ScriptBytecodeAdapter.getMethodPointer(appender.get(), (String)ShortTypeHandling.castToString(new GStringImpl(new Object[] { oldName }, new String[] { "", "" })));ScriptBytecodeAdapter.setProperty(localClosure, null, arrayOfCallSite[0].callGroovyObjectGetProperty(appenderDelegate.get()), (String)ShortTypeHandling.castToString(new GStringImpl(new Object[] { newName }, new String[] { "", "" })));return localClosure;return null; }
public Object call(Object oldName, Object newName) { CallSite[] arrayOfCallSite = $getCallSiteArray();
return arrayOfCallSite[1].callCurrent(this, oldName, newName);
return null; }
public AppenderDelegate getAppenderDelegate() { CallSite[] arrayOfCallSite = $getCallSiteArray();
return (AppenderDelegate)ScriptBytecodeAdapter.castToType(appenderDelegate.get(), AppenderDelegate.class);
return null; }
public Appender getAppender() { CallSite[] arrayOfCallSite = $getCallSiteArray();
return (Appender)ScriptBytecodeAdapter.castToType(appender.get(), Appender.class);
return null; } }
public void turboFilter(Class clazz, Closure closure) { CallSite[] arrayOfCallSite = $getCallSiteArray();arrayOfCallSite[90].callCurrent(this, arrayOfCallSite[91].call(arrayOfCallSite[92].call("About to instantiate turboFilter of type [", arrayOfCallSite[93].callGetProperty(clazz)), "]"));
TurboFilter turboFilter = (TurboFilter)ScriptBytecodeAdapter.castToType(arrayOfCallSite[94].call(clazz), TurboFilter.class);
Object localObject1 = arrayOfCallSite[95].callGroovyObjectGetProperty(this);ScriptBytecodeAdapter.setProperty(localObject1, null, turboFilter, "context");
if (ScriptBytecodeAdapter.compareNotEqual(closure, null)) {
ComponentDelegate componentDelegate = (ComponentDelegate)ScriptBytecodeAdapter.castToType(arrayOfCallSite[96].callConstructor(ComponentDelegate.class, turboFilter), ComponentDelegate.class);
Object localObject2 = arrayOfCallSite[97].callGroovyObjectGetProperty(this);ScriptBytecodeAdapter.setGroovyObjectProperty(localObject2, ConfigurationDelegate.class, componentDelegate, "context");
ComponentDelegate localComponentDelegate1 = componentDelegate;ScriptBytecodeAdapter.setGroovyObjectProperty(localComponentDelegate1, ConfigurationDelegate.class, closure, "delegate");
Object localObject3 = arrayOfCallSite[98].callGetProperty(Closure.class);ScriptBytecodeAdapter.setGroovyObjectProperty(localObject3, ConfigurationDelegate.class, closure, "resolveStrategy");
arrayOfCallSite[99].call(closure);
}
arrayOfCallSite[100].call(turboFilter);
arrayOfCallSite[101].callCurrent(this, "Adding aforementioned turbo filter to context");
arrayOfCallSite[102].call(arrayOfCallSite[103].callGroovyObjectGetProperty(this), turboFilter);
}
public String timestamp(String datePattern, long timeReference) {
CallSite[] arrayOfCallSite = $getCallSiteArray();long now = DefaultTypeTransformation.longUnbox(Integer.valueOf(-1));
Object localObject;
if (ScriptBytecodeAdapter.compareEqual(Long.valueOf(timeReference), Integer.valueOf(-1))) {
arrayOfCallSite[104].callCurrent(this, "Using current interpretation time, i.e. now, as time reference.");
localObject = arrayOfCallSite[105].call(System.class);now = DefaultTypeTransformation.longUnbox(localObject);
} else {
long l1 = timeReference;now = l1;
arrayOfCallSite[106].callCurrent(this, arrayOfCallSite[107].call(arrayOfCallSite[108].call("Using ", Long.valueOf(now)), " as time reference."));
}
CachingDateFormatter sdf = (CachingDateFormatter)ScriptBytecodeAdapter.castToType(arrayOfCallSite[109].callConstructor(CachingDateFormatter.class, datePattern), CachingDateFormatter.class);
return (String)ShortTypeHandling.castToString(arrayOfCallSite[110].call(sdf, Long.valueOf(now)));return null;
}
public void jmxConfigurator(String name)
{
CallSite[] arrayOfCallSite = $getCallSiteArray();Object objectName = null;
Object contextName = arrayOfCallSite[111].callGetProperty(arrayOfCallSite[112].callGroovyObjectGetProperty(this));
if (ScriptBytecodeAdapter.compareNotEqual(name, null))
try {
String str;
try { localObject1 = arrayOfCallSite[113].callConstructor(ObjectName.class, name);objectName = localObject1;
} catch (MalformedObjectNameException e) { Object localObject1;
str = name;contextName = str;
}
} finally {}
if (ScriptBytecodeAdapter.compareEqual(objectName, null)) {
Object objectNameAsStr = arrayOfCallSite[114].call(MBeanUtil.class, contextName, JMXConfigurator.class);
Object localObject3 = arrayOfCallSite[115].call(MBeanUtil.class, arrayOfCallSite[116].callGroovyObjectGetProperty(this), this, objectNameAsStr);objectName = localObject3;
if (ScriptBytecodeAdapter.compareEqual(objectName, null)) {
arrayOfCallSite[117].callCurrent(this, new GStringImpl(new Object[] { objectNameAsStr }, new String[] { "Failed to construct ObjectName for [", "]" }));
return;
}
}
Object platformMBeanServer = arrayOfCallSite[118].callGetProperty(ManagementFactory.class);
if ((!DefaultTypeTransformation.booleanUnbox(arrayOfCallSite[119].call(MBeanUtil.class, platformMBeanServer, objectName)) ? 1 : 0) != 0) {
JMXConfigurator jmxConfigurator = (JMXConfigurator)ScriptBytecodeAdapter.castToType(arrayOfCallSite[120].callConstructor(JMXConfigurator.class, ScriptBytecodeAdapter.createPojoWrapper((LoggerContext)ScriptBytecodeAdapter.castToType(arrayOfCallSite[121].callGroovyObjectGetProperty(this), LoggerContext.class), LoggerContext.class), platformMBeanServer, objectName), JMXConfigurator.class);
try {
try { arrayOfCallSite[122].call(platformMBeanServer, jmxConfigurator, objectName);
} catch (Exception all) {
arrayOfCallSite[123].callCurrent(this, "Failed to create mbean", all);
}
}
finally {}
}
}
public void scan()
{
CallSite[] arrayOfCallSite = $getCallSiteArray();
if ((__$stMC) || (BytecodeInterface8.disabledStandardMetaClass()))
{
scan(null);
null;
}
else
{
scan(null);
null;
}
}
public void logger(String name, Level level, List<String> appenderNames)
{
CallSite[] arrayOfCallSite = $getCallSiteArray();
logger(name, level, appenderNames, null);
null;
}
public void appender(String name, Class clazz)
{
CallSite[] arrayOfCallSite = $getCallSiteArray();
appender(name, clazz, null);
null;
}
public void receiver(String name, Class aClass)
{
CallSite[] arrayOfCallSite = $getCallSiteArray();
receiver(name, aClass, null);
null;
}
public void turboFilter(Class clazz)
{
CallSite[] arrayOfCallSite = $getCallSiteArray();
turboFilter(clazz, null);
null;
}
public String timestamp(String datePattern)
{
CallSite[] arrayOfCallSite = $getCallSiteArray();
if ((__$stMC) || (BytecodeInterface8.disabledStandardMetaClass())) {
return timestamp(datePattern, DefaultTypeTransformation.longUnbox(Integer.valueOf(-1)));
} else {
return timestamp(datePattern, DefaultTypeTransformation.longUnbox(Integer.valueOf(-1)));
}
return null;
}
public void jmxConfigurator()
{
CallSite[] arrayOfCallSite = $getCallSiteArray();
if ((__$stMC) || (BytecodeInterface8.disabledStandardMetaClass()))
{
jmxConfigurator(null);
null;
}
else
{
jmxConfigurator(null);
null;
}
}
public List<Appender> getAppenderList()
{
return appenderList;
}
public void setAppenderList(List<Appender> paramList)
{
appenderList = paramList;
}
}

View File

@ -0,0 +1,161 @@
package ch.qos.logback.classic.gaffer;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.core.joran.util.ConfigurationWatchListUtil;
import ch.qos.logback.core.status.OnConsoleStatusListener;
import ch.qos.logback.core.util.ContextUtil;
import groovy.lang.Binding;
import groovy.lang.Closure;
import groovy.lang.GroovyObject;
import groovy.lang.MetaClass;
import groovy.lang.Reference;
import groovy.lang.Script;
import java.io.File;
import java.net.URL;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.codehaus.groovy.control.customizers.ImportCustomizer;
import org.codehaus.groovy.runtime.ArrayUtil;
import org.codehaus.groovy.runtime.BytecodeInterface8;
import org.codehaus.groovy.runtime.GStringImpl;
import org.codehaus.groovy.runtime.GeneratedClosure;
import org.codehaus.groovy.runtime.ScriptBytecodeAdapter;
import org.codehaus.groovy.runtime.callsite.CallSite;
import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation;
public class GafferConfigurator implements GroovyObject
{
private LoggerContext context;
private static final String DEBUG_SYSTEM_PROPERTY_KEY = "logback.debug";
public GafferConfigurator(LoggerContext arg1)
{
LoggerContext context;
CallSite[] arrayOfCallSite = $getCallSiteArray();MetaClass localMetaClass = $getStaticMetaClass();metaClass = localMetaClass;LoggerContext localLoggerContext1 = context;this.context = ((LoggerContext)ScriptBytecodeAdapter.castToType(localLoggerContext1, LoggerContext.class));
}
protected void informContextOfURLUsedForConfiguration(URL url) {
CallSite[] arrayOfCallSite = $getCallSiteArray();arrayOfCallSite[0].call(ConfigurationWatchListUtil.class, context, url);
}
public void run(URL url) {
CallSite[] arrayOfCallSite = $getCallSiteArray(); if ((__$stMC) || (BytecodeInterface8.disabledStandardMetaClass())) { arrayOfCallSite[1].callCurrent(this, url); } else { informContextOfURLUsedForConfiguration(url);null; }
arrayOfCallSite[2].callCurrent(this, arrayOfCallSite[3].callGetProperty(url));
}
public void run(File file) {
CallSite[] arrayOfCallSite = $getCallSiteArray();arrayOfCallSite[4].callCurrent(this, arrayOfCallSite[5].call(arrayOfCallSite[6].call(file)));
arrayOfCallSite[7].callCurrent(this, arrayOfCallSite[8].callGetProperty(file));
}
class _run_closure1
extends Closure
implements GeneratedClosure
{
public _run_closure1(Object _thisObject, Reference dslScript)
{
super(_thisObject);
Reference localReference = dslScript;
this.dslScript = localReference;
}
public Object doCall(Object it)
{
CallSite[] arrayOfCallSite = $getCallSiteArray();return dslScript.get();return null;
}
public Script getDslScript()
{
CallSite[] arrayOfCallSite = $getCallSiteArray();
return (Script)ScriptBytecodeAdapter.castToType(dslScript.get(), Script.class);
return null;
}
public Object doCall()
{
CallSite[] arrayOfCallSite = $getCallSiteArray();
return doCall(null);
return null;
}
}
public void run(String dslText)
{
CallSite[] arrayOfCallSite = $getCallSiteArray();Binding binding = (Binding)ScriptBytecodeAdapter.castToType(arrayOfCallSite[9].callConstructor(Binding.class), Binding.class);
arrayOfCallSite[10].call(binding, "hostname", arrayOfCallSite[11].callGetProperty(ContextUtil.class));
Object configuration = arrayOfCallSite[12].callConstructor(CompilerConfiguration.class);
if ((__$stMC) || (BytecodeInterface8.disabledStandardMetaClass())) arrayOfCallSite[13].call(configuration, arrayOfCallSite[14].callCurrent(this)); else { arrayOfCallSite[15].call(configuration, importCustomizer());
}
String debugAttrib = (String)org.codehaus.groovy.runtime.typehandling.ShortTypeHandling.castToString(arrayOfCallSite[16].call(System.class, DEBUG_SYSTEM_PROPERTY_KEY));
if (((DefaultTypeTransformation.booleanUnbox(arrayOfCallSite[17].call(ch.qos.logback.core.util.OptionHelper.class, debugAttrib))) || (DefaultTypeTransformation.booleanUnbox(arrayOfCallSite[18].call(debugAttrib, "false"))) ? 1 : 0) == 0) {}
if ((DefaultTypeTransformation.booleanUnbox(arrayOfCallSite[19].call(debugAttrib, "null")) ? 1 : 0) == 0)
{
arrayOfCallSite[20].call(OnConsoleStatusListener.class, context);
}
arrayOfCallSite[21].call(arrayOfCallSite[22].callConstructor(ContextUtil.class, context), arrayOfCallSite[23].call(context));
Reference dslScript = new Reference((Script)ScriptBytecodeAdapter.castToType(arrayOfCallSite[24].call(arrayOfCallSite[25].callConstructor(groovy.lang.GroovyShell.class, binding, configuration), dslText), Script.class));
arrayOfCallSite[26].call(arrayOfCallSite[27].callGroovyObjectGetProperty((Script)dslScript.get()), ConfigurationDelegate.class);
arrayOfCallSite[28].call((Script)dslScript.get(), context);
_run_closure1 local_run_closure1 = new _run_closure1(this, dslScript);ScriptBytecodeAdapter.setProperty(local_run_closure1, null, arrayOfCallSite[29].callGroovyObjectGetProperty((Script)dslScript.get()), "getDeclaredOrigin");
arrayOfCallSite[30].call((Script)dslScript.get());
}
protected ImportCustomizer importCustomizer() {
CallSite[] arrayOfCallSite = $getCallSiteArray();Object customizer = arrayOfCallSite[31].callConstructor(ImportCustomizer.class);
Object core = "ch.qos.logback.core";
arrayOfCallSite[32].call(customizer, ArrayUtil.createArray(core, new GStringImpl(new Object[] { core }, new String[] { "", ".encoder" }), new GStringImpl(new Object[] { core }, new String[] { "", ".read" }), new GStringImpl(new Object[] { core }, new String[] { "", ".rolling" }), new GStringImpl(new Object[] { core }, new String[] { "", ".status" }), "ch.qos.logback.classic.net"));
arrayOfCallSite[33].call(customizer, arrayOfCallSite[34].callGetProperty(PatternLayoutEncoder.class));
arrayOfCallSite[35].call(customizer, arrayOfCallSite[36].callGetProperty(Level.class));
arrayOfCallSite[37].call(customizer, "off", arrayOfCallSite[38].callGetProperty(Level.class), "OFF");
arrayOfCallSite[39].call(customizer, "error", arrayOfCallSite[40].callGetProperty(Level.class), "ERROR");
arrayOfCallSite[41].call(customizer, "warn", arrayOfCallSite[42].callGetProperty(Level.class), "WARN");
arrayOfCallSite[43].call(customizer, "info", arrayOfCallSite[44].callGetProperty(Level.class), "INFO");
arrayOfCallSite[45].call(customizer, "debug", arrayOfCallSite[46].callGetProperty(Level.class), "DEBUG");
arrayOfCallSite[47].call(customizer, "trace", arrayOfCallSite[48].callGetProperty(Level.class), "TRACE");
arrayOfCallSite[49].call(customizer, "all", arrayOfCallSite[50].callGetProperty(Level.class), "ALL");
return (ImportCustomizer)ScriptBytecodeAdapter.castToType(customizer, ImportCustomizer.class);return null;
}
public LoggerContext getContext()
{
return context;
}
public void setContext(LoggerContext paramLoggerContext)
{
context = paramLoggerContext;
}
public static final String getDEBUG_SYSTEM_PROPERTY_KEY()
{
return DEBUG_SYSTEM_PROPERTY_KEY;
}
}

View File

@ -0,0 +1,78 @@
package ch.qos.logback.classic.gaffer;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.status.ErrorStatus;
import ch.qos.logback.core.status.StatusManager;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
public class GafferUtil
{
public GafferUtil() {}
private static String ERROR_MSG = "Failed to instantiate ch.qos.logback.classic.gaffer.GafferConfigurator";
public static void runGafferConfiguratorOn(LoggerContext loggerContext, Object origin, File configFile) {
GafferConfigurator gafferConfigurator = newGafferConfiguratorInstance(loggerContext, origin);
if (gafferConfigurator != null) {
gafferConfigurator.run(configFile);
}
}
public static void runGafferConfiguratorOn(LoggerContext loggerContext, Object origin, URL configFile) {
GafferConfigurator gafferConfigurator = newGafferConfiguratorInstance(loggerContext, origin);
if (gafferConfigurator != null) {
gafferConfigurator.run(configFile);
}
}
private static GafferConfigurator newGafferConfiguratorInstance(LoggerContext loggerContext, Object origin)
{
try {
Class gcClass = Class.forName("ch.qos.logback.classic.gaffer.GafferConfigurator");
Constructor c = gcClass.getConstructor(new Class[] { LoggerContext.class });
return (GafferConfigurator)c.newInstance(new Object[] { loggerContext });
} catch (ClassNotFoundException e) {
addError(loggerContext, origin, ERROR_MSG, e);
} catch (NoSuchMethodException e) {
addError(loggerContext, origin, ERROR_MSG, e);
} catch (InvocationTargetException e) {
addError(loggerContext, origin, ERROR_MSG, e);
} catch (InstantiationException e) {
addError(loggerContext, origin, ERROR_MSG, e);
} catch (IllegalAccessException e) {
addError(loggerContext, origin, ERROR_MSG, e);
}
return null;
}
private static void addError(LoggerContext context, Object origin, String msg) {
addError(context, origin, msg, null);
}
private static void addError(LoggerContext context, Object origin, String msg, Throwable t) {
StatusManager sm = context.getStatusManager();
if (sm == null) {
return;
}
sm.add(new ErrorStatus(msg, origin, t));
}
}

View File

@ -0,0 +1,48 @@
package ch.qos.logback.classic.gaffer;
import groovy.lang.GroovyObject;
import groovy.lang.MetaClass;
import java.util.LinkedHashMap;
import org.codehaus.groovy.runtime.ScriptBytecodeAdapter;
import org.codehaus.groovy.runtime.callsite.CallSite;
import org.codehaus.groovy.runtime.typehandling.ShortTypeHandling;
import org.codehaus.groovy.transform.ImmutableASTTransformation;
public enum NestingType
implements GroovyObject
{
public static final NestingType MIN_VALUE;
public static final NestingType MAX_VALUE;
public NestingType(LinkedHashMap __namedArgs)
{
MetaClass localMetaClass = $getStaticMetaClass();
metaClass = localMetaClass;
if (ScriptBytecodeAdapter.compareEqual(__namedArgs, null)) {
throw ((Throwable)arrayOfCallSite[0].callConstructor(IllegalArgumentException.class, "One of the enum constants for enum ch.qos.logback.classic.gaffer.NestingType was initialized with null. Please use a non-null value or define your own constructor."));
} else {
arrayOfCallSite[1].callStatic(ImmutableASTTransformation.class, this, __namedArgs);
}
}
public NestingType()
{
this((LinkedHashMap)ScriptBytecodeAdapter.castToType(arrayOfCallSite[2].callConstructor(LinkedHashMap.class), LinkedHashMap.class));
}
static
{
Object localObject1 = $getCallSiteArray()[13].callStatic(NestingType.class, "NA", Integer.valueOf(0));
NA = (NestingType)ShortTypeHandling.castToEnum(localObject1, NestingType.class);
Object localObject2 = $getCallSiteArray()[14].callStatic(NestingType.class, "SINGLE", Integer.valueOf(1));
SINGLE = (NestingType)ShortTypeHandling.castToEnum(localObject2, NestingType.class);
Object localObject3 = $getCallSiteArray()[15].callStatic(NestingType.class, "AS_COLLECTION", Integer.valueOf(2));
AS_COLLECTION = (NestingType)ShortTypeHandling.castToEnum(localObject3, NestingType.class);
NestingType localNestingType1 = NA;
MIN_VALUE = localNestingType1;
NestingType localNestingType2 = AS_COLLECTION;
MAX_VALUE = localNestingType2;
NestingType[] arrayOfNestingType = { NA, SINGLE, AS_COLLECTION };
$VALUES = arrayOfNestingType;
}
}

View File

@ -0,0 +1,77 @@
package ch.qos.logback.classic.gaffer;
import groovy.lang.Closure;
import groovy.lang.GroovyObject;
import groovy.lang.MetaClass;
import java.beans.Introspector;
import org.codehaus.groovy.runtime.BytecodeInterface8;
import org.codehaus.groovy.runtime.GStringImpl;
import org.codehaus.groovy.runtime.GeneratedClosure;
import org.codehaus.groovy.runtime.ScriptBytecodeAdapter;
import org.codehaus.groovy.runtime.callsite.CallSite;
import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation;
import org.codehaus.groovy.runtime.typehandling.ShortTypeHandling;
public class PropertyUtil implements GroovyObject
{
public PropertyUtil()
{
PropertyUtil this;
CallSite[] arrayOfCallSite = $getCallSiteArray();
MetaClass localMetaClass = $getStaticMetaClass();
metaClass = localMetaClass;
}
public static boolean hasAdderMethod(Object obj, String name)
{
CallSite[] arrayOfCallSite = $getCallSiteArray();String addMethod = null; GStringImpl localGStringImpl1; GStringImpl localGStringImpl2; if ((__$stMC) || (BytecodeInterface8.disabledStandardMetaClass())) { localGStringImpl1 = new GStringImpl(new Object[] { arrayOfCallSite[0].callStatic(PropertyUtil.class, name) }, new String[] { "add", "" });addMethod = (String)ShortTypeHandling.castToString(localGStringImpl1); } else { localGStringImpl2 = new GStringImpl(new Object[] { upperCaseFirstLetter(name) }, new String[] { "add", "" });addMethod = (String)ShortTypeHandling.castToString(localGStringImpl2); }
return DefaultTypeTransformation.booleanUnbox(arrayOfCallSite[1].call(arrayOfCallSite[2].callGetProperty(obj), obj, addMethod));return DefaultTypeTransformation.booleanUnbox(Integer.valueOf(0));
}
public static NestingType nestingType(Object obj, String name) {
CallSite[] arrayOfCallSite = $getCallSiteArray();Object decapitalizedName = arrayOfCallSite[3].call(Introspector.class, name);
if (DefaultTypeTransformation.booleanUnbox(arrayOfCallSite[4].call(obj, decapitalizedName))) {
return (NestingType)ShortTypeHandling.castToEnum(arrayOfCallSite[5].callGetProperty(NestingType.class), NestingType.class);
}
if (DefaultTypeTransformation.booleanUnbox(arrayOfCallSite[6].callStatic(PropertyUtil.class, obj, name))) {
return (NestingType)ShortTypeHandling.castToEnum(arrayOfCallSite[7].callGetProperty(NestingType.class), NestingType.class);
}
return (NestingType)ShortTypeHandling.castToEnum(arrayOfCallSite[8].callGetProperty(NestingType.class), NestingType.class);return null;
}
public static void attach(NestingType nestingType, Object component, Object subComponent, String name) {
CallSite[] arrayOfCallSite = $getCallSiteArray();NestingType localNestingType = nestingType;
if (ScriptBytecodeAdapter.isCase(localNestingType, arrayOfCallSite[9].callGetProperty(NestingType.class))) {
Object localObject1 = arrayOfCallSite[10].call(Introspector.class, name);name = (String)ShortTypeHandling.castToString(localObject1);
Object localObject2 = subComponent;ScriptBytecodeAdapter.setProperty(localObject2, null, component, (String)ShortTypeHandling.castToString(new GStringImpl(new Object[] { name }, new String[] { "", "" })));
return;
} else if (!ScriptBytecodeAdapter.isCase(localNestingType, arrayOfCallSite[11].callGetProperty(NestingType.class))) { return; }
String firstUpperName = (String)ShortTypeHandling.castToString(arrayOfCallSite[12].call(PropertyUtil.class, name));
ScriptBytecodeAdapter.invokeMethodN(PropertyUtil.class, component, (String)ShortTypeHandling.castToString(new GStringImpl(new Object[] { firstUpperName }, new String[] { "add", "" })), new Object[] { subComponent });
}
public static String transformFirstLetter(String s, Closure closure)
{
CallSite[] arrayOfCallSite = $getCallSiteArray(); if ((!BytecodeInterface8.isOrigInt()) || (!BytecodeInterface8.isOrigZ()) || (__$stMC) || (BytecodeInterface8.disabledStandardMetaClass())) { if (((ScriptBytecodeAdapter.compareEqual(s, null)) || (ScriptBytecodeAdapter.compareEqual(arrayOfCallSite[13].call(s), Integer.valueOf(0))) ? 1 : 0) != 0) {
return s;
}
}
else if (((ScriptBytecodeAdapter.compareEqual(s, null)) || (ScriptBytecodeAdapter.compareEqual(arrayOfCallSite[14].call(s), Integer.valueOf(0))) ? 1 : 0) != 0) {
return s;
}
String firstLetter = (String)ShortTypeHandling.castToString(arrayOfCallSite[15].callConstructor(String.class, arrayOfCallSite[16].call(s, Integer.valueOf(0))));
String modifiedFistLetter = (String)ShortTypeHandling.castToString(arrayOfCallSite[17].call(closure, firstLetter));
if (ScriptBytecodeAdapter.compareEqual(arrayOfCallSite[18].call(s), Integer.valueOf(1))) {
return modifiedFistLetter;
} else
return (String)ShortTypeHandling.castToString(arrayOfCallSite[19].call(modifiedFistLetter, arrayOfCallSite[20].call(s, Integer.valueOf(1)))); return null;
}
class _upperCaseFirstLetter_closure1 extends Closure implements GeneratedClosure { public _upperCaseFirstLetter_closure1(Object _thisObject) { super(_thisObject); }
public Object doCall(String it) { CallSite[] arrayOfCallSite = $getCallSiteArray();return arrayOfCallSite[0].call(it);return null; } public Object call(String it) { CallSite[] arrayOfCallSite = $getCallSiteArray(); if ((__$stMC) || (BytecodeInterface8.disabledStandardMetaClass())) return arrayOfCallSite[1].callCurrent(this, it); else return doCall(it); return null; } } public static String upperCaseFirstLetter(String s) { CallSite[] arrayOfCallSite = $getCallSiteArray();return (String)ShortTypeHandling.castToString(arrayOfCallSite[21].callStatic(PropertyUtil.class, s, new _upperCaseFirstLetter_closure1(PropertyUtil.class, PropertyUtil.class)));return null;
}
}

View File

@ -0,0 +1,94 @@
package ch.qos.logback.classic.helpers;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.MDC;
public class MDCInsertingServletFilter
implements Filter
{
public MDCInsertingServletFilter() {}
public void destroy() {}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException
{
insertIntoMDC(request);
try {
chain.doFilter(request, response);
} finally {
clearMDC();
}
}
void insertIntoMDC(ServletRequest request)
{
MDC.put("req.remoteHost", request.getRemoteHost());
if ((request instanceof HttpServletRequest)) {
HttpServletRequest httpServletRequest = (HttpServletRequest)request;
MDC.put("req.requestURI", httpServletRequest.getRequestURI());
StringBuffer requestURL = httpServletRequest.getRequestURL();
if (requestURL != null) {
MDC.put("req.requestURL", requestURL.toString());
}
MDC.put("req.method", httpServletRequest.getMethod());
MDC.put("req.queryString", httpServletRequest.getQueryString());
MDC.put("req.userAgent", httpServletRequest.getHeader("User-Agent"));
MDC.put("req.xForwardedFor", httpServletRequest.getHeader("X-Forwarded-For"));
}
}
void clearMDC()
{
MDC.remove("req.remoteHost");
MDC.remove("req.requestURI");
MDC.remove("req.queryString");
MDC.remove("req.requestURL");
MDC.remove("req.method");
MDC.remove("req.userAgent");
MDC.remove("req.xForwardedFor");
}
public void init(FilterConfig arg0)
throws ServletException
{}
}

View File

@ -0,0 +1,75 @@
package ch.qos.logback.classic.html;
import ch.qos.logback.core.CoreConstants;
import ch.qos.logback.core.html.CssBuilder;
public class DefaultCssBuilder
implements CssBuilder
{
public DefaultCssBuilder() {}
public void addCss(StringBuilder sbuf)
{
sbuf.append("<style type=\"text/css\">");
sbuf.append(CoreConstants.LINE_SEPARATOR);
sbuf.append("table { margin-left: 2em; margin-right: 2em; border-left: 2px solid #AAA; }");
sbuf.append(CoreConstants.LINE_SEPARATOR);
sbuf.append("TR.even { background: #FFFFFF; }");
sbuf.append(CoreConstants.LINE_SEPARATOR);
sbuf.append("TR.odd { background: #EAEAEA; }");
sbuf.append(CoreConstants.LINE_SEPARATOR);
sbuf.append("TR.warn TD.Level, TR.error TD.Level, TR.fatal TD.Level {font-weight: bold; color: #FF4040 }");
sbuf.append(CoreConstants.LINE_SEPARATOR);
sbuf.append("TD { padding-right: 1ex; padding-left: 1ex; border-right: 2px solid #AAA; }");
sbuf.append(CoreConstants.LINE_SEPARATOR);
sbuf.append("TD.Time, TD.Date { text-align: right; font-family: courier, monospace; font-size: smaller; }");
sbuf.append(CoreConstants.LINE_SEPARATOR);
sbuf.append("TD.Thread { text-align: left; }");
sbuf.append(CoreConstants.LINE_SEPARATOR);
sbuf.append("TD.Level { text-align: right; }");
sbuf.append(CoreConstants.LINE_SEPARATOR);
sbuf.append("TD.Logger { text-align: left; }");
sbuf.append(CoreConstants.LINE_SEPARATOR);
sbuf.append("TR.header { background: #596ED5; color: #FFF; font-weight: bold; font-size: larger; }");
sbuf.append(CoreConstants.LINE_SEPARATOR);
sbuf.append("TD.Exception { background: #A2AEE8; font-family: courier, monospace;}");
sbuf.append(CoreConstants.LINE_SEPARATOR);
sbuf.append("</style>");
sbuf.append(CoreConstants.LINE_SEPARATOR);
}
}

View File

@ -0,0 +1,67 @@
package ch.qos.logback.classic.html;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.classic.spi.StackTraceElementProxy;
import ch.qos.logback.core.CoreConstants;
import ch.qos.logback.core.helpers.Transform;
import ch.qos.logback.core.html.IThrowableRenderer;
public class DefaultThrowableRenderer
implements IThrowableRenderer<ILoggingEvent>
{
static final String TRACE_PREFIX = "<br />&nbsp;&nbsp;&nbsp;&nbsp;";
public DefaultThrowableRenderer() {}
public void render(StringBuilder sbuf, ILoggingEvent event)
{
IThrowableProxy tp = event.getThrowableProxy();
sbuf.append("<tr><td class=\"Exception\" colspan=\"6\">");
while (tp != null) {
render(sbuf, tp);
tp = tp.getCause();
}
sbuf.append("</td></tr>");
}
void render(StringBuilder sbuf, IThrowableProxy tp) {
printFirstLine(sbuf, tp);
int commonFrames = tp.getCommonFrames();
StackTraceElementProxy[] stepArray = tp.getStackTraceElementProxyArray();
for (int i = 0; i < stepArray.length - commonFrames; i++) {
StackTraceElementProxy step = stepArray[i];
sbuf.append("<br />&nbsp;&nbsp;&nbsp;&nbsp;");
sbuf.append(Transform.escapeTags(step.toString()));
sbuf.append(CoreConstants.LINE_SEPARATOR);
}
if (commonFrames > 0) {
sbuf.append("<br />&nbsp;&nbsp;&nbsp;&nbsp;");
sbuf.append("\t... ").append(commonFrames).append(" common frames omitted").append(CoreConstants.LINE_SEPARATOR);
}
}
public void printFirstLine(StringBuilder sb, IThrowableProxy tp)
{
int commonFrames = tp.getCommonFrames();
if (commonFrames > 0) {
sb.append("<br />").append("Caused by: ");
}
sb.append(tp.getClassName()).append(": ").append(Transform.escapeTags(tp.getMessage()));
sb.append(CoreConstants.LINE_SEPARATOR);
}
}

View File

@ -0,0 +1,142 @@
package ch.qos.logback.classic.html;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.PatternLayout;
import ch.qos.logback.classic.pattern.MDCConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.CoreConstants;
import ch.qos.logback.core.helpers.Transform;
import ch.qos.logback.core.html.HTMLLayoutBase;
import ch.qos.logback.core.html.IThrowableRenderer;
import ch.qos.logback.core.pattern.Converter;
import java.util.Map;
public class HTMLLayout
extends HTMLLayoutBase<ILoggingEvent>
{
static final String DEFAULT_CONVERSION_PATTERN = "%date%thread%level%logger%mdc%msg";
IThrowableRenderer<ILoggingEvent> throwableRenderer;
public HTMLLayout()
{
pattern = "%date%thread%level%logger%mdc%msg";
throwableRenderer = new DefaultThrowableRenderer();
cssBuilder = new DefaultCssBuilder();
}
public void start()
{
int errorCount = 0;
if (throwableRenderer == null) {
addError("ThrowableRender cannot be null.");
errorCount++;
}
if (errorCount == 0) {
super.start();
}
}
protected Map<String, String> getDefaultConverterMap() {
return PatternLayout.defaultConverterMap;
}
public String doLayout(ILoggingEvent event) {
StringBuilder buf = new StringBuilder();
startNewTableIfLimitReached(buf);
boolean odd = true;
if ((counter++ & 1L) == 0L) {
odd = false;
}
String level = event.getLevel().toString().toLowerCase();
buf.append(CoreConstants.LINE_SEPARATOR);
buf.append("<tr class=\"");
buf.append(level);
if (odd) {
buf.append(" odd\">");
} else {
buf.append(" even\">");
}
buf.append(CoreConstants.LINE_SEPARATOR);
Converter<ILoggingEvent> c = head;
while (c != null) {
appendEventToBuffer(buf, c, event);
c = c.getNext();
}
buf.append("</tr>");
buf.append(CoreConstants.LINE_SEPARATOR);
if (event.getThrowableProxy() != null) {
throwableRenderer.render(buf, event);
}
return buf.toString();
}
private void appendEventToBuffer(StringBuilder buf, Converter<ILoggingEvent> c, ILoggingEvent event)
{
buf.append("<td class=\"");
buf.append(computeConverterName(c));
buf.append("\">");
buf.append(Transform.escapeTags(c.convert(event)));
buf.append("</td>");
buf.append(CoreConstants.LINE_SEPARATOR);
}
public IThrowableRenderer getThrowableRenderer() {
return throwableRenderer;
}
public void setThrowableRenderer(IThrowableRenderer<ILoggingEvent> throwableRenderer) {
this.throwableRenderer = throwableRenderer;
}
protected String computeConverterName(Converter c)
{
if ((c instanceof MDCConverter)) {
MDCConverter mc = (MDCConverter)c;
String key = mc.getFirstOption();
if (key != null) {
return key;
}
return "MDC";
}
return super.computeConverterName(c);
}
}

View File

@ -0,0 +1,43 @@
package ch.qos.logback.classic.html;
import ch.qos.logback.core.html.CssBuilder;
public class UrlCssBuilder
implements CssBuilder
{
public UrlCssBuilder() {}
String url = "http://logback.qos.ch/css/classic.css";
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public void addCss(StringBuilder sbuf) {
sbuf.append("<link REL=StyleSheet HREF=\"");
sbuf.append(url);
sbuf.append("\" TITLE=\"Basic\" />");
}
}

View File

@ -0,0 +1,300 @@
package ch.qos.logback.classic.jmx;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.classic.spi.LoggerContextListener;
import ch.qos.logback.classic.util.ContextInitializer;
import ch.qos.logback.core.Context;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.spi.ContextAwareBase;
import ch.qos.logback.core.status.Status;
import ch.qos.logback.core.status.StatusListener;
import ch.qos.logback.core.status.StatusListenerAsList;
import ch.qos.logback.core.status.StatusManager;
import ch.qos.logback.core.util.StatusPrinter;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.ObjectName;
public class JMXConfigurator
extends ContextAwareBase
implements JMXConfiguratorMBean, LoggerContextListener
{
private static String EMPTY = "";
LoggerContext loggerContext;
MBeanServer mbs;
ObjectName objectName;
String objectNameAsString;
boolean debug = true;
boolean started;
public JMXConfigurator(LoggerContext loggerContext, MBeanServer mbs, ObjectName objectName)
{
started = true;
context = loggerContext;
this.loggerContext = loggerContext;
this.mbs = mbs;
this.objectName = objectName;
objectNameAsString = objectName.toString();
if (previouslyRegisteredListenerWithSameObjectName()) {
addError("Previously registered JMXConfigurator named [" + objectNameAsString + "] in the logger context named [" + loggerContext.getName() + "]");
}
else
{
loggerContext.addListener(this);
}
}
private boolean previouslyRegisteredListenerWithSameObjectName() {
List<LoggerContextListener> lcll = loggerContext.getCopyOfListenerList();
for (LoggerContextListener lcl : lcll) {
if ((lcl instanceof JMXConfigurator)) {
JMXConfigurator jmxConfigurator = (JMXConfigurator)lcl;
if (objectName.equals(objectName)) {
return true;
}
}
}
return false;
}
public void reloadDefaultConfiguration() throws JoranException {
ContextInitializer ci = new ContextInitializer(loggerContext);
URL url = ci.findURLOfDefaultConfigurationFile(true);
reloadByURL(url);
}
public void reloadByFileName(String fileName) throws JoranException, FileNotFoundException
{
File f = new File(fileName);
if ((f.exists()) && (f.isFile()))
{
try {
URL url = f.toURI().toURL();
reloadByURL(url);
} catch (MalformedURLException e) {
throw new RuntimeException("Unexpected MalformedURLException occured. See nexted cause.", e);
}
}
else
{
String errMsg = "Could not find [" + fileName + "]";
addInfo(errMsg);
throw new FileNotFoundException(errMsg);
}
}
void addStatusListener(StatusListener statusListener) {
StatusManager sm = loggerContext.getStatusManager();
sm.add(statusListener);
}
void removeStatusListener(StatusListener statusListener) {
StatusManager sm = loggerContext.getStatusManager();
sm.remove(statusListener);
}
public void reloadByURL(URL url) throws JoranException {
StatusListenerAsList statusListenerAsList = new StatusListenerAsList();
addStatusListener(statusListenerAsList);
addInfo("Resetting context: " + loggerContext.getName());
loggerContext.reset();
addStatusListener(statusListenerAsList);
try
{
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(loggerContext);
configurator.doConfigure(url);
addInfo("Context: " + loggerContext.getName() + " reloaded.");
} finally {
removeStatusListener(statusListenerAsList);
if (debug) {
StatusPrinter.print(statusListenerAsList.getStatusList());
}
}
}
public void setLoggerLevel(String loggerName, String levelStr) {
if (loggerName == null) {
return;
}
if (levelStr == null) {
return;
}
loggerName = loggerName.trim();
levelStr = levelStr.trim();
addInfo("Trying to set level " + levelStr + " to logger " + loggerName);
LoggerContext lc = (LoggerContext)context;
Logger logger = lc.getLogger(loggerName);
if ("null".equalsIgnoreCase(levelStr)) {
logger.setLevel(null);
} else {
Level level = Level.toLevel(levelStr, null);
if (level != null) {
logger.setLevel(level);
}
}
}
public String getLoggerLevel(String loggerName) {
if (loggerName == null) {
return EMPTY;
}
loggerName = loggerName.trim();
LoggerContext lc = (LoggerContext)context;
Logger logger = lc.exists(loggerName);
if ((logger != null) && (logger.getLevel() != null)) {
return logger.getLevel().toString();
}
return EMPTY;
}
public String getLoggerEffectiveLevel(String loggerName)
{
if (loggerName == null) {
return EMPTY;
}
loggerName = loggerName.trim();
LoggerContext lc = (LoggerContext)context;
Logger logger = lc.exists(loggerName);
if (logger != null) {
return logger.getEffectiveLevel().toString();
}
return EMPTY;
}
public List<String> getLoggerList()
{
LoggerContext lc = (LoggerContext)context;
List<String> strList = new ArrayList();
Iterator<Logger> it = lc.getLoggerList().iterator();
while (it.hasNext()) {
Logger log = (Logger)it.next();
strList.add(log.getName());
}
return strList;
}
public List<String> getStatuses() {
List<String> list = new ArrayList();
Iterator<Status> it = context.getStatusManager().getCopyOfStatusList().iterator();
while (it.hasNext()) {
list.add(((Status)it.next()).toString());
}
return list;
}
public void onStop(LoggerContext context)
{
if (!started) {
addInfo("onStop() method called on a stopped JMXActivator [" + objectNameAsString + "]");
return;
}
if (mbs.isRegistered(objectName)) {
try {
addInfo("Unregistering mbean [" + objectNameAsString + "]");
mbs.unregisterMBean(objectName);
}
catch (InstanceNotFoundException e) {
addError("Unable to find a verifiably registered mbean [" + objectNameAsString + "]", e);
}
catch (MBeanRegistrationException e) {
addError("Failed to unregister [" + objectNameAsString + "]", e);
}
} else {
addInfo("mbean [" + objectNameAsString + "] was not in the mbean registry. This is OK.");
}
stop();
}
public void onLevelChange(Logger logger, Level level) {}
public void onReset(LoggerContext context)
{
addInfo("onReset() method called JMXActivator [" + objectNameAsString + "]");
}
public boolean isResetResistant()
{
return true;
}
private void clearFields() {
mbs = null;
objectName = null;
loggerContext = null;
}
private void stop() {
started = false;
clearFields();
}
public void onStart(LoggerContext context) {}
public String toString()
{
return getClass().getName() + "(" + context.getName() + ")";
}
}

View File

@ -0,0 +1,28 @@
package ch.qos.logback.classic.jmx;
import ch.qos.logback.core.joran.spi.JoranException;
import java.io.FileNotFoundException;
import java.net.URL;
import java.util.List;
public abstract interface JMXConfiguratorMBean
{
public abstract void reloadDefaultConfiguration()
throws JoranException;
public abstract void reloadByFileName(String paramString)
throws JoranException, FileNotFoundException;
public abstract void reloadByURL(URL paramURL)
throws JoranException;
public abstract void setLoggerLevel(String paramString1, String paramString2);
public abstract String getLoggerLevel(String paramString);
public abstract String getLoggerEffectiveLevel(String paramString);
public abstract List<String> getLoggerList();
public abstract List<String> getStatuses();
}

View File

@ -0,0 +1,88 @@
package ch.qos.logback.classic.jmx;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.Context;
import ch.qos.logback.core.status.StatusUtil;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
public class MBeanUtil
{
static final String DOMAIN = "ch.qos.logback.classic";
public MBeanUtil() {}
public static String getObjectNameFor(String contextName, Class type)
{
return "ch.qos.logback.classic:Name=" + contextName + ",Type=" + type.getName();
}
public static ObjectName string2ObjectName(Context context, Object caller, String objectNameAsStr)
{
String msg = "Failed to convert [" + objectNameAsStr + "] to ObjectName";
StatusUtil statusUtil = new StatusUtil(context);
try {
return new ObjectName(objectNameAsStr);
} catch (MalformedObjectNameException e) {
statusUtil.addError(caller, msg, e);
return null;
} catch (NullPointerException e) {
statusUtil.addError(caller, msg, e); }
return null;
}
public static boolean isRegistered(MBeanServer mbs, ObjectName objectName)
{
return mbs.isRegistered(objectName);
}
public static void createAndRegisterJMXConfigurator(MBeanServer mbs, LoggerContext loggerContext, JMXConfigurator jmxConfigurator, ObjectName objectName, Object caller)
{
try
{
mbs.registerMBean(jmxConfigurator, objectName);
} catch (Exception e) {
StatusUtil statusUtil = new StatusUtil(loggerContext);
statusUtil.addError(caller, "Failed to create mbean", e);
}
}
public static void unregister(LoggerContext loggerContext, MBeanServer mbs, ObjectName objectName, Object caller)
{
StatusUtil statusUtil = new StatusUtil(loggerContext);
if (mbs.isRegistered(objectName)) {
try {
statusUtil.addInfo(caller, "Unregistering mbean [" + objectName + "]");
mbs.unregisterMBean(objectName);
}
catch (InstanceNotFoundException e) {
statusUtil.addError(caller, "Failed to unregister mbean" + objectName, e);
}
catch (MBeanRegistrationException e)
{
statusUtil.addError(caller, "Failed to unregister mbean" + objectName, e);
}
} else {
statusUtil.addInfo(caller, "mbean [" + objectName + "] does not seem to be registered");
}
}
}

View File

@ -0,0 +1,95 @@
package ch.qos.logback.classic.joran;
import ch.qos.logback.classic.joran.action.ConfigurationAction;
import ch.qos.logback.classic.joran.action.ConsolePluginAction;
import ch.qos.logback.classic.joran.action.ContextNameAction;
import ch.qos.logback.classic.joran.action.EvaluatorAction;
import ch.qos.logback.classic.joran.action.InsertFromJNDIAction;
import ch.qos.logback.classic.joran.action.JMXConfiguratorAction;
import ch.qos.logback.classic.joran.action.LevelAction;
import ch.qos.logback.classic.joran.action.LoggerAction;
import ch.qos.logback.classic.joran.action.LoggerContextListenerAction;
import ch.qos.logback.classic.joran.action.ReceiverAction;
import ch.qos.logback.classic.joran.action.RootLoggerAction;
import ch.qos.logback.classic.sift.SiftAction;
import ch.qos.logback.classic.spi.PlatformInfo;
import ch.qos.logback.classic.util.DefaultNestedComponentRules;
import ch.qos.logback.core.joran.JoranConfiguratorBase;
import ch.qos.logback.core.joran.action.AppenderRefAction;
import ch.qos.logback.core.joran.action.IncludeAction;
import ch.qos.logback.core.joran.action.NOPAction;
import ch.qos.logback.core.joran.conditional.ElseAction;
import ch.qos.logback.core.joran.conditional.IfAction;
import ch.qos.logback.core.joran.conditional.ThenAction;
import ch.qos.logback.core.joran.spi.DefaultNestedComponentRegistry;
import ch.qos.logback.core.joran.spi.ElementSelector;
import ch.qos.logback.core.joran.spi.RuleStore;
public class JoranConfigurator
extends JoranConfiguratorBase
{
public JoranConfigurator() {}
public void addInstanceRules(RuleStore rs)
{
super.addInstanceRules(rs);
rs.addRule(new ElementSelector("configuration"), new ConfigurationAction());
rs.addRule(new ElementSelector("configuration/contextName"), new ContextNameAction());
rs.addRule(new ElementSelector("configuration/contextListener"), new LoggerContextListenerAction());
rs.addRule(new ElementSelector("configuration/insertFromJNDI"), new InsertFromJNDIAction());
rs.addRule(new ElementSelector("configuration/evaluator"), new EvaluatorAction());
rs.addRule(new ElementSelector("configuration/appender/sift"), new SiftAction());
rs.addRule(new ElementSelector("configuration/appender/sift/*"), new NOPAction());
rs.addRule(new ElementSelector("configuration/logger"), new LoggerAction());
rs.addRule(new ElementSelector("configuration/logger/level"), new LevelAction());
rs.addRule(new ElementSelector("configuration/root"), new RootLoggerAction());
rs.addRule(new ElementSelector("configuration/root/level"), new LevelAction());
rs.addRule(new ElementSelector("configuration/logger/appender-ref"), new AppenderRefAction());
rs.addRule(new ElementSelector("configuration/root/appender-ref"), new AppenderRefAction());
rs.addRule(new ElementSelector("*/if"), new IfAction());
rs.addRule(new ElementSelector("*/if/then"), new ThenAction());
rs.addRule(new ElementSelector("*/if/then/*"), new NOPAction());
rs.addRule(new ElementSelector("*/if/else"), new ElseAction());
rs.addRule(new ElementSelector("*/if/else/*"), new NOPAction());
if (PlatformInfo.hasJMXObjectName()) {
rs.addRule(new ElementSelector("configuration/jmxConfigurator"), new JMXConfiguratorAction());
}
rs.addRule(new ElementSelector("configuration/include"), new IncludeAction());
rs.addRule(new ElementSelector("configuration/consolePlugin"), new ConsolePluginAction());
rs.addRule(new ElementSelector("configuration/receiver"), new ReceiverAction());
}
protected void addDefaultNestedComponentRegistryRules(DefaultNestedComponentRegistry registry)
{
DefaultNestedComponentRules.addDefaultNestedComponentRegistryRules(registry);
}
}

View File

@ -0,0 +1,109 @@
package ch.qos.logback.classic.joran.action;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.turbo.ReconfigureOnChangeFilter;
import ch.qos.logback.classic.util.EnvUtil;
import ch.qos.logback.core.joran.action.Action;
import ch.qos.logback.core.joran.spi.InterpretationContext;
import ch.qos.logback.core.status.OnConsoleStatusListener;
import ch.qos.logback.core.util.ContextUtil;
import ch.qos.logback.core.util.Duration;
import ch.qos.logback.core.util.OptionHelper;
import org.xml.sax.Attributes;
public class ConfigurationAction
extends Action
{
static final String INTERNAL_DEBUG_ATTR = "debug";
static final String SCAN_ATTR = "scan";
static final String SCAN_PERIOD_ATTR = "scanPeriod";
static final String DEBUG_SYSTEM_PROPERTY_KEY = "logback.debug";
public ConfigurationAction() {}
long threshold = 0L;
public void begin(InterpretationContext ic, String name, Attributes attributes) {
threshold = System.currentTimeMillis();
String debugAttrib = getSystemProperty("logback.debug");
if (debugAttrib == null) {
debugAttrib = ic.subst(attributes.getValue("debug"));
}
if ((OptionHelper.isEmpty(debugAttrib)) || (debugAttrib.equalsIgnoreCase("false")) || (debugAttrib.equalsIgnoreCase("null")))
{
addInfo("debug attribute not set");
} else {
OnConsoleStatusListener.addNewInstanceToContext(context);
}
processScanAttrib(ic, attributes);
ContextUtil contextUtil = new ContextUtil(context);
contextUtil.addHostNameAsProperty();
if (EnvUtil.isGroovyAvailable()) {
LoggerContext lc = (LoggerContext)context;
contextUtil.addGroovyPackages(lc.getFrameworkPackages());
}
ic.pushObject(getContext());
}
String getSystemProperty(String name)
{
try
{
return System.getProperty(name);
} catch (SecurityException ex) {}
return null;
}
void processScanAttrib(InterpretationContext ic, Attributes attributes)
{
String scanAttrib = ic.subst(attributes.getValue("scan"));
if ((!OptionHelper.isEmpty(scanAttrib)) && (!"false".equalsIgnoreCase(scanAttrib)))
{
ReconfigureOnChangeFilter rocf = new ReconfigureOnChangeFilter();
rocf.setContext(context);
String scanPeriodAttrib = ic.subst(attributes.getValue("scanPeriod"));
if (!OptionHelper.isEmpty(scanPeriodAttrib)) {
try {
Duration duration = Duration.valueOf(scanPeriodAttrib);
rocf.setRefreshPeriod(duration.getMilliseconds());
addInfo("Setting ReconfigureOnChangeFilter scanning period to " + duration);
}
catch (NumberFormatException nfe) {
addError("Error while converting [" + scanAttrib + "] to long", nfe);
}
}
rocf.start();
LoggerContext lc = (LoggerContext)context;
addInfo("Adding ReconfigureOnChangeFilter as a turbo filter");
lc.addTurboFilter(rocf);
}
}
public void end(InterpretationContext ec, String name) {
addInfo("End of configuration.");
ec.popObject();
}
}

View File

@ -0,0 +1,63 @@
package ch.qos.logback.classic.joran.action;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.net.SocketAppender;
import ch.qos.logback.core.joran.action.Action;
import ch.qos.logback.core.joran.spi.ActionException;
import ch.qos.logback.core.joran.spi.InterpretationContext;
import org.xml.sax.Attributes;
public class ConsolePluginAction
extends Action
{
private static final String PORT_ATTR = "port";
private static final Integer DEFAULT_PORT = Integer.valueOf(4321);
public ConsolePluginAction() {}
public void begin(InterpretationContext ec, String name, Attributes attributes) throws ActionException {
String portStr = attributes.getValue("port");
Integer port = null;
if (portStr == null) {
port = DEFAULT_PORT;
} else {
try {
port = Integer.valueOf(portStr);
} catch (NumberFormatException ex) {
addError("Port " + portStr + " in ConsolePlugin config is not a correct number");
}
}
LoggerContext lc = (LoggerContext)ec.getContext();
SocketAppender appender = new SocketAppender();
appender.setContext(lc);
appender.setIncludeCallerData(true);
appender.setRemoteHost("localhost");
appender.setPort(port.intValue());
appender.start();
Logger root = lc.getLogger("ROOT");
root.addAppender(appender);
addInfo("Sending LoggingEvents to the plugin using port " + port);
}
public void end(InterpretationContext ec, String name)
throws ActionException
{}
}

View File

@ -0,0 +1,38 @@
package ch.qos.logback.classic.joran.action;
import ch.qos.logback.core.Context;
import ch.qos.logback.core.joran.action.Action;
import ch.qos.logback.core.joran.spi.InterpretationContext;
import org.xml.sax.Attributes;
public class ContextNameAction
extends Action
{
public ContextNameAction() {}
public void begin(InterpretationContext ec, String name, Attributes attributes) {}
public void body(InterpretationContext ec, String body)
{
String finalBody = ec.subst(body);
addInfo("Setting logger context name as [" + finalBody + "]");
try {
context.setName(finalBody);
} catch (IllegalStateException e) {
addError("Failed to rename context [" + context.getName() + "] as [" + finalBody + "]", e);
}
}
public void end(InterpretationContext ec, String name) {}
}

View File

@ -0,0 +1,23 @@
package ch.qos.logback.classic.joran.action;
import ch.qos.logback.classic.boolex.JaninoEventEvaluator;
import ch.qos.logback.core.joran.action.AbstractEventEvaluatorAction;
public class EvaluatorAction
extends AbstractEventEvaluatorAction
{
public EvaluatorAction() {}
protected String defaultClassName()
{
return JaninoEventEvaluator.class.getName();
}
}

View File

@ -0,0 +1,81 @@
package ch.qos.logback.classic.joran.action;
import ch.qos.logback.classic.util.JNDIUtil;
import ch.qos.logback.core.joran.action.Action;
import ch.qos.logback.core.joran.action.ActionUtil;
import ch.qos.logback.core.joran.action.ActionUtil.Scope;
import ch.qos.logback.core.joran.spi.InterpretationContext;
import ch.qos.logback.core.util.OptionHelper;
import javax.naming.Context;
import javax.naming.NamingException;
import org.xml.sax.Attributes;
public class InsertFromJNDIAction
extends Action
{
public static final String ENV_ENTRY_NAME_ATTR = "env-entry-name";
public static final String AS_ATTR = "as";
public InsertFromJNDIAction() {}
public void begin(InterpretationContext ec, String name, Attributes attributes)
{
int errorCount = 0;
String envEntryName = ec.subst(attributes.getValue("env-entry-name"));
String asKey = ec.subst(attributes.getValue("as"));
String scopeStr = attributes.getValue("scope");
ActionUtil.Scope scope = ActionUtil.stringToScope(scopeStr);
if (OptionHelper.isEmpty(envEntryName)) {
String lineColStr = getLineColStr(ec);
addError("[env-entry-name] missing, around " + lineColStr);
errorCount++;
}
if (OptionHelper.isEmpty(asKey)) {
String lineColStr = getLineColStr(ec);
addError("[as] missing, around " + lineColStr);
errorCount++;
}
if (errorCount != 0) {
return;
}
try
{
Context ctx = JNDIUtil.getInitialContext();
String envEntryValue = JNDIUtil.lookup(ctx, envEntryName);
if (OptionHelper.isEmpty(envEntryValue)) {
addError("[" + envEntryName + "] has null or empty value");
} else {
addInfo("Setting variable [" + asKey + "] to [" + envEntryValue + "] in [" + scope + "] scope");
ActionUtil.setProperty(ec, asKey, envEntryValue, scope);
}
} catch (NamingException e) {
addError("Failed to lookup JNDI env-entry [" + envEntryName + "]");
}
}
public void end(InterpretationContext ec, String name) {}
}

View File

@ -0,0 +1,86 @@
package ch.qos.logback.classic.joran.action;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.jmx.JMXConfigurator;
import ch.qos.logback.classic.jmx.MBeanUtil;
import ch.qos.logback.core.Context;
import ch.qos.logback.core.joran.action.Action;
import ch.qos.logback.core.joran.spi.ActionException;
import ch.qos.logback.core.joran.spi.InterpretationContext;
import ch.qos.logback.core.util.OptionHelper;
import java.lang.management.ManagementFactory;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.xml.sax.Attributes;
public class JMXConfiguratorAction
extends Action
{
static final String OBJECT_NAME_ATTRIBUTE_NAME = "objectName";
static final String CONTEXT_NAME_ATTRIBUTE_NAME = "contextName";
static final char JMX_NAME_SEPARATOR = ',';
public JMXConfiguratorAction() {}
public void begin(InterpretationContext ec, String name, Attributes attributes)
throws ActionException
{
addInfo("begin");
String contextName = context.getName();
String contextNameAttributeVal = attributes.getValue("contextName");
if (!OptionHelper.isEmpty(contextNameAttributeVal)) {
contextName = contextNameAttributeVal;
}
String objectNameAttributeVal = attributes.getValue("objectName");
String objectNameAsStr;
String objectNameAsStr; if (OptionHelper.isEmpty(objectNameAttributeVal)) {
objectNameAsStr = MBeanUtil.getObjectNameFor(contextName, JMXConfigurator.class);
}
else {
objectNameAsStr = objectNameAttributeVal;
}
ObjectName objectName = MBeanUtil.string2ObjectName(context, this, objectNameAsStr);
if (objectName == null) {
addError("Failed construct ObjectName for [" + objectNameAsStr + "]");
return;
}
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
if (!MBeanUtil.isRegistered(mbs, objectName))
{
JMXConfigurator jmxConfigurator = new JMXConfigurator((LoggerContext)context, mbs, objectName);
try
{
mbs.registerMBean(jmxConfigurator, objectName);
} catch (Exception e) {
addError("Failed to create mbean", e);
}
}
}
public void end(InterpretationContext ec, String name)
throws ActionException
{}
}

View File

@ -0,0 +1,65 @@
package ch.qos.logback.classic.joran.action;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.core.joran.action.Action;
import ch.qos.logback.core.joran.spi.InterpretationContext;
import org.xml.sax.Attributes;
public class LevelAction
extends Action
{
public LevelAction() {}
boolean inError = false;
public void begin(InterpretationContext ec, String name, Attributes attributes) {
Object o = ec.peekObject();
if (!(o instanceof Logger)) {
inError = true;
addError("For element <level>, could not find a logger at the top of execution stack.");
return;
}
Logger l = (Logger)o;
String loggerName = l.getName();
String levelStr = ec.subst(attributes.getValue("value"));
if (("INHERITED".equalsIgnoreCase(levelStr)) || ("NULL".equalsIgnoreCase(levelStr))) {
l.setLevel(null);
} else {
l.setLevel(Level.toLevel(levelStr, Level.DEBUG));
}
addInfo(loggerName + " level set to " + l.getLevel());
}
public void finish(InterpretationContext ec) {}
public void end(InterpretationContext ec, String e) {}
}

View File

@ -0,0 +1,94 @@
package ch.qos.logback.classic.joran.action;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.joran.action.Action;
import ch.qos.logback.core.joran.spi.InterpretationContext;
import ch.qos.logback.core.util.OptionHelper;
import org.xml.sax.Attributes;
public class LoggerAction
extends Action
{
public static final String LEVEL_ATTRIBUTE = "level";
boolean inError = false;
public LoggerAction() {}
public void begin(InterpretationContext ec, String name, Attributes attributes) { inError = false;
logger = null;
LoggerContext loggerContext = (LoggerContext)context;
String loggerName = ec.subst(attributes.getValue("name"));
if (OptionHelper.isEmpty(loggerName)) {
inError = true;
String aroundLine = getLineColStr(ec);
String errorMsg = "No 'name' attribute in element " + name + ", around " + aroundLine;
addError(errorMsg);
return;
}
logger = loggerContext.getLogger(loggerName);
String levelStr = ec.subst(attributes.getValue("level"));
if (!OptionHelper.isEmpty(levelStr)) {
if (("INHERITED".equalsIgnoreCase(levelStr)) || ("NULL".equalsIgnoreCase(levelStr)))
{
addInfo("Setting level of logger [" + loggerName + "] to null, i.e. INHERITED");
logger.setLevel(null);
} else {
Level level = Level.toLevel(levelStr);
addInfo("Setting level of logger [" + loggerName + "] to " + level);
logger.setLevel(level);
}
}
String additivityStr = ec.subst(attributes.getValue("additivity"));
if (!OptionHelper.isEmpty(additivityStr)) {
boolean additive = OptionHelper.toBoolean(additivityStr, true);
addInfo("Setting additivity of logger [" + loggerName + "] to " + additive);
logger.setAdditive(additive);
}
ec.pushObject(logger);
}
Logger logger;
public void end(InterpretationContext ec, String e) { if (inError) {
return;
}
Object o = ec.peekObject();
if (o != logger) {
addWarn("The object on the top the of the stack is not " + logger + " pushed earlier");
addWarn("It is: " + o);
} else {
ec.popObject();
}
}
public void finish(InterpretationContext ec) {}
}

View File

@ -0,0 +1,81 @@
package ch.qos.logback.classic.joran.action;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.LoggerContextListener;
import ch.qos.logback.core.joran.action.Action;
import ch.qos.logback.core.joran.spi.ActionException;
import ch.qos.logback.core.joran.spi.InterpretationContext;
import ch.qos.logback.core.spi.ContextAware;
import ch.qos.logback.core.spi.LifeCycle;
import ch.qos.logback.core.util.OptionHelper;
import org.xml.sax.Attributes;
public class LoggerContextListenerAction
extends Action
{
boolean inError = false;
LoggerContextListener lcl;
public LoggerContextListenerAction() {}
public void begin(InterpretationContext ec, String name, Attributes attributes) throws ActionException
{
inError = false;
String className = attributes.getValue("class");
if (OptionHelper.isEmpty(className)) {
addError("Mandatory \"class\" attribute not set for <loggerContextListener> element");
inError = true;
return;
}
try
{
lcl = ((LoggerContextListener)OptionHelper.instantiateByClassName(className, LoggerContextListener.class, context));
if ((lcl instanceof ContextAware)) {
((ContextAware)lcl).setContext(context);
}
ec.pushObject(lcl);
addInfo("Adding LoggerContextListener of type [" + className + "] to the object stack");
}
catch (Exception oops)
{
inError = true;
addError("Could not create LoggerContextListener of type " + className + "].", oops);
}
}
public void end(InterpretationContext ec, String name) throws ActionException
{
if (inError) {
return;
}
Object o = ec.peekObject();
if (o != lcl) {
addWarn("The object on the top the of the stack is not the LoggerContextListener pushed earlier.");
} else {
if ((lcl instanceof LifeCycle)) {
((LifeCycle)lcl).start();
addInfo("Starting LoggerContextListener");
}
((LoggerContext)context).addListener(lcl);
ec.popObject();
}
}
}

View File

@ -0,0 +1,80 @@
package ch.qos.logback.classic.joran.action;
import ch.qos.logback.classic.net.ReceiverBase;
import ch.qos.logback.core.Context;
import ch.qos.logback.core.joran.action.Action;
import ch.qos.logback.core.joran.spi.ActionException;
import ch.qos.logback.core.joran.spi.InterpretationContext;
import ch.qos.logback.core.util.OptionHelper;
import org.xml.sax.Attributes;
public class ReceiverAction
extends Action
{
private ReceiverBase receiver;
private boolean inError;
public ReceiverAction() {}
public void begin(InterpretationContext ic, String name, Attributes attributes)
throws ActionException
{
String className = attributes.getValue("class");
if (OptionHelper.isEmpty(className)) {
addError("Missing class name for receiver. Near [" + name + "] line " + getLineNumber(ic));
inError = true;
return;
}
try
{
addInfo("About to instantiate receiver of type [" + className + "]");
receiver = ((ReceiverBase)OptionHelper.instantiateByClassName(className, ReceiverBase.class, context));
receiver.setContext(context);
ic.pushObject(receiver);
}
catch (Exception ex) {
inError = true;
addError("Could not create a receiver of type [" + className + "].", ex);
throw new ActionException(ex);
}
}
public void end(InterpretationContext ic, String name)
throws ActionException
{
if (inError) { return;
}
ic.getContext().register(receiver);
receiver.start();
Object o = ic.peekObject();
if (o != receiver) {
addWarn("The object at the of the stack is not the remote pushed earlier.");
}
else {
ic.popObject();
}
}
}

View File

@ -0,0 +1,60 @@
package ch.qos.logback.classic.joran.action;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.joran.action.Action;
import ch.qos.logback.core.joran.spi.InterpretationContext;
import ch.qos.logback.core.util.OptionHelper;
import org.xml.sax.Attributes;
public class RootLoggerAction
extends Action
{
Logger root;
public RootLoggerAction() {}
boolean inError = false;
public void begin(InterpretationContext ec, String name, Attributes attributes) {
inError = false;
LoggerContext loggerContext = (LoggerContext)context;
root = loggerContext.getLogger("ROOT");
String levelStr = ec.subst(attributes.getValue("level"));
if (!OptionHelper.isEmpty(levelStr)) {
Level level = Level.toLevel(levelStr);
addInfo("Setting level of ROOT logger to " + level);
root.setLevel(level);
}
ec.pushObject(root);
}
public void end(InterpretationContext ec, String name) {
if (inError) {
return;
}
Object o = ec.peekObject();
if (o != root) {
addWarn("The object on the top the of the stack is not the root logger");
addWarn("It is: " + o);
} else {
ec.popObject();
}
}
public void finish(InterpretationContext ec) {}
}

View File

@ -0,0 +1,73 @@
package ch.qos.logback.classic.jul;
public class JULHelper
{
public JULHelper() {}
public static final boolean isRegularNonRootLogger(java.util.logging.Logger julLogger)
{
if (julLogger == null)
return false;
return !julLogger.getName().equals("");
}
public static final boolean isRoot(java.util.logging.Logger julLogger) {
if (julLogger == null)
return false;
return julLogger.getName().equals("");
}
public static java.util.logging.Level asJULLevel(ch.qos.logback.classic.Level lbLevel) {
if (lbLevel == null) {
throw new IllegalArgumentException("Unexpected level [null]");
}
switch (levelInt) {
case -2147483648:
return java.util.logging.Level.ALL;
case 5000:
return java.util.logging.Level.FINEST;
case 10000:
return java.util.logging.Level.FINE;
case 20000:
return java.util.logging.Level.INFO;
case 30000:
return java.util.logging.Level.WARNING;
case 40000:
return java.util.logging.Level.SEVERE;
case 2147483647:
return java.util.logging.Level.OFF;
}
throw new IllegalArgumentException("Unexpected level [" + lbLevel + "]");
}
public static String asJULLoggerName(String loggerName)
{
if ("ROOT".equals(loggerName)) {
return "";
}
return loggerName;
}
public static java.util.logging.Logger asJULLogger(String loggerName) {
String julLoggerName = asJULLoggerName(loggerName);
return java.util.logging.Logger.getLogger(julLoggerName);
}
public static java.util.logging.Logger asJULLogger(ch.qos.logback.classic.Logger logger) {
return asJULLogger(logger.getName());
}
}

View File

@ -0,0 +1,110 @@
package ch.qos.logback.classic.jul;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.LoggerContextListener;
import ch.qos.logback.core.spi.ContextAwareBase;
import ch.qos.logback.core.spi.LifeCycle;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.LogManager;
public class LevelChangePropagator
extends ContextAwareBase
implements LoggerContextListener, LifeCycle
{
public LevelChangePropagator() {}
private Set julLoggerSet = new HashSet();
boolean isStarted = false;
boolean resetJUL = false;
public void setResetJUL(boolean resetJUL) {
this.resetJUL = resetJUL;
}
public boolean isResetResistant() {
return false;
}
public void onStart(LoggerContext context) {}
public void onReset(LoggerContext context) {}
public void onStop(LoggerContext context) {}
public void onLevelChange(ch.qos.logback.classic.Logger logger, ch.qos.logback.classic.Level level)
{
propagate(logger, level);
}
private void propagate(ch.qos.logback.classic.Logger logger, ch.qos.logback.classic.Level level) {
addInfo("Propagating " + level + " level on " + logger + " onto the JUL framework");
java.util.logging.Logger julLogger = JULHelper.asJULLogger(logger);
julLoggerSet.add(julLogger);
java.util.logging.Level julLevel = JULHelper.asJULLevel(level);
julLogger.setLevel(julLevel);
}
public void resetJULLevels() {
LogManager lm = LogManager.getLogManager();
Enumeration e = lm.getLoggerNames();
while (e.hasMoreElements()) {
String loggerName = (String)e.nextElement();
java.util.logging.Logger julLogger = lm.getLogger(loggerName);
if ((JULHelper.isRegularNonRootLogger(julLogger)) && (julLogger.getLevel() != null)) {
addInfo("Setting level of jul logger [" + loggerName + "] to null");
julLogger.setLevel(null);
}
}
}
private void propagateExistingLoggerLevels() {
LoggerContext loggerContext = (LoggerContext)context;
List<ch.qos.logback.classic.Logger> loggerList = loggerContext.getLoggerList();
for (ch.qos.logback.classic.Logger l : loggerList) {
if (l.getLevel() != null) {
propagate(l, l.getLevel());
}
}
}
public void start() {
if (resetJUL) {
resetJULLevels();
}
propagateExistingLoggerLevels();
isStarted = true;
}
public void stop() {
isStarted = false;
}
public boolean isStarted() {
return isStarted;
}
}

View File

@ -0,0 +1,186 @@
package ch.qos.logback.classic.log4j;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.classic.spi.StackTraceElementProxy;
import ch.qos.logback.core.LayoutBase;
import ch.qos.logback.core.helpers.Transform;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class XMLLayout
extends LayoutBase<ILoggingEvent>
{
private final int DEFAULT_SIZE = 256;
private final int UPPER_LIMIT = 2048;
private StringBuilder buf = new StringBuilder(256);
private boolean locationInfo = false;
private boolean properties = false;
public XMLLayout() {}
public void start() { super.start(); }
public void setLocationInfo(boolean flag)
{
locationInfo = flag;
}
public boolean getLocationInfo()
{
return locationInfo;
}
public void setProperties(boolean flag)
{
properties = flag;
}
public boolean getProperties()
{
return properties;
}
public String doLayout(ILoggingEvent event)
{
if (buf.capacity() > 2048) {
buf = new StringBuilder(256);
} else {
buf.setLength(0);
}
buf.append("<log4j:event logger=\"");
buf.append(Transform.escapeTags(event.getLoggerName()));
buf.append("\"\r\n");
buf.append(" timestamp=\"");
buf.append(event.getTimeStamp());
buf.append("\" level=\"");
buf.append(event.getLevel());
buf.append("\" thread=\"");
buf.append(Transform.escapeTags(event.getThreadName()));
buf.append("\">\r\n");
buf.append(" <log4j:message>");
buf.append(Transform.escapeTags(event.getFormattedMessage()));
buf.append("</log4j:message>\r\n");
IThrowableProxy tp = event.getThrowableProxy();
if (tp != null) {
StackTraceElementProxy[] stepArray = tp.getStackTraceElementProxyArray();
buf.append(" <log4j:throwable><![CDATA[");
for (StackTraceElementProxy step : stepArray) {
buf.append('\t');
buf.append(step.toString());
buf.append("\r\n");
}
buf.append("]]></log4j:throwable>\r\n");
}
if (locationInfo) {
StackTraceElement[] callerDataArray = event.getCallerData();
if ((callerDataArray != null) && (callerDataArray.length > 0)) {
StackTraceElement immediateCallerData = callerDataArray[0];
buf.append(" <log4j:locationInfo class=\"");
buf.append(immediateCallerData.getClassName());
buf.append("\"\r\n");
buf.append(" method=\"");
buf.append(Transform.escapeTags(immediateCallerData.getMethodName()));
buf.append("\" file=\"");
buf.append(Transform.escapeTags(immediateCallerData.getFileName()));
buf.append("\" line=\"");
buf.append(immediateCallerData.getLineNumber());
buf.append("\"/>\r\n");
}
}
if (getProperties()) {
Map<String, String> propertyMap = event.getMDCPropertyMap();
if ((propertyMap != null) && (propertyMap.size() != 0)) {
Set<Map.Entry<String, String>> entrySet = propertyMap.entrySet();
buf.append(" <log4j:properties>");
for (Map.Entry<String, String> entry : entrySet) {
buf.append("\r\n <log4j:data");
buf.append(" name='" + Transform.escapeTags((String)entry.getKey()) + "'");
buf.append(" value='" + Transform.escapeTags((String)entry.getValue()) + "'");
buf.append(" />");
}
buf.append("\r\n </log4j:properties>");
}
}
buf.append("\r\n</log4j:event>\r\n\r\n");
return buf.toString();
}
public String getContentType()
{
return "text/xml";
}
}

View File

@ -0,0 +1,211 @@
package ch.qos.logback.classic.net;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.net.JMSAppenderBase;
import ch.qos.logback.core.spi.PreSerializationTransformer;
import java.io.Serializable;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.naming.Context;
public class JMSQueueAppender
extends JMSAppenderBase<ILoggingEvent>
{
static int SUCCESSIVE_FAILURE_LIMIT = 3;
String queueBindingName;
String qcfBindingName;
QueueConnection queueConnection;
QueueSession queueSession;
QueueSender queueSender;
int successiveFailureCount = 0;
private PreSerializationTransformer<ILoggingEvent> pst = new LoggingEventPreSerializationTransformer();
public JMSQueueAppender() {}
public void setQueueConnectionFactoryBindingName(String qcfBindingName)
{
this.qcfBindingName = qcfBindingName;
}
public String getQueueConnectionFactoryBindingName()
{
return qcfBindingName;
}
public void setQueueBindingName(String queueBindingName)
{
this.queueBindingName = queueBindingName;
}
public String getQueueBindingName()
{
return queueBindingName;
}
public void start()
{
try
{
Context jndi = buildJNDIContext();
QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory)lookup(jndi, qcfBindingName);
if (userName != null) {
queueConnection = queueConnectionFactory.createQueueConnection(userName, password);
}
else {
queueConnection = queueConnectionFactory.createQueueConnection();
}
queueSession = queueConnection.createQueueSession(false, 1);
Queue queue = (Queue)lookup(jndi, queueBindingName);
queueSender = queueSession.createSender(queue);
queueConnection.start();
jndi.close();
} catch (Exception e) {
addError("Error while activating options for appender named [" + name + "].", e);
}
if ((queueConnection != null) && (queueSession != null) && (queueSender != null))
{
super.start();
}
}
public synchronized void stop()
{
if (!started) {
return;
}
started = false;
try
{
if (queueSession != null) {
queueSession.close();
}
if (queueConnection != null) {
queueConnection.close();
}
} catch (Exception e) {
addError("Error while closing JMSAppender [" + name + "].", e);
}
queueSender = null;
queueSession = null;
queueConnection = null;
}
public void append(ILoggingEvent event)
{
if (!isStarted()) {
return;
}
try
{
ObjectMessage msg = queueSession.createObjectMessage();
Serializable so = pst.transform(event);
msg.setObject(so);
queueSender.send(msg);
successiveFailureCount = 0;
} catch (Exception e) {
successiveFailureCount += 1;
if (successiveFailureCount > SUCCESSIVE_FAILURE_LIMIT) {
stop();
}
addError("Could not send message in JMSQueueAppender [" + name + "].", e);
}
}
protected QueueConnection getQueueConnection()
{
return queueConnection;
}
protected QueueSession getQueueSession()
{
return queueSession;
}
protected QueueSender getQueueSender()
{
return queueSender;
}
}

View File

@ -0,0 +1,152 @@
package ch.qos.logback.classic.net;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.util.ContextInitializer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.Properties;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSession;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NameNotFoundException;
import javax.naming.NamingException;
import org.slf4j.LoggerFactory;
public class JMSQueueSink
implements MessageListener
{
private Logger logger = (Logger)LoggerFactory.getLogger(JMSTopicSink.class);
public static void main(String[] args) throws Exception {
if (args.length < 2) {
usage("Wrong number of arguments.");
}
String qcfBindingName = args[0];
String queueBindingName = args[1];
String username = null;
String password = null;
if (args.length == 4) {
username = args[2];
password = args[3];
}
LoggerContext loggerContext = (LoggerContext)LoggerFactory.getILoggerFactory();
new ContextInitializer(loggerContext).autoConfig();
new JMSQueueSink(qcfBindingName, queueBindingName, username, password);
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Type \"exit\" to quit JMSQueueSink.");
for (;;) {
String s = stdin.readLine();
if (s.equalsIgnoreCase("exit")) {
System.out.println("Exiting. Kill the application if it does not exit due to daemon threads.");
return;
}
}
}
public JMSQueueSink(String qcfBindingName, String queueBindingName, String username, String password)
{
try
{
Properties env = new Properties();
env.put("java.naming.factory.initial", "org.apache.activemq.jndi.ActiveMQInitialContextFactory");
env.put("java.naming.provider.url", "tcp://localhost:61616");
Context ctx = new InitialContext(env);
QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory)lookup(ctx, qcfBindingName);
System.out.println("Queue Cnx Factory found");
Queue queue = (Queue)ctx.lookup(queueBindingName);
System.out.println("Queue found: " + queue.getQueueName());
QueueConnection queueConnection = queueConnectionFactory.createQueueConnection(username, password);
System.out.println("Queue Connection created");
QueueSession queueSession = queueConnection.createQueueSession(false, 1);
MessageConsumer queueConsumer = queueSession.createConsumer(queue);
queueConsumer.setMessageListener(this);
queueConnection.start();
System.out.println("Queue Connection started");
}
catch (Exception e) {
logger.error("Could not read JMS message.", e);
}
}
public void onMessage(Message message)
{
try {
if ((message instanceof ObjectMessage)) {
ObjectMessage objectMessage = (ObjectMessage)message;
ILoggingEvent event = (ILoggingEvent)objectMessage.getObject();
Logger log = (Logger)LoggerFactory.getLogger(event.getLoggerName());
log.callAppenders(event);
} else {
logger.warn("Received message is of type " + message.getJMSType() + ", was expecting ObjectMessage.");
}
}
catch (JMSException jmse) {
logger.error("Exception thrown while processing incoming message.", jmse);
}
}
protected Object lookup(Context ctx, String name) throws NamingException
{
try {
return ctx.lookup(name);
} catch (NameNotFoundException e) {
logger.error("Could not find name [" + name + "].");
throw e;
}
}
static void usage(String msg) {
System.err.println(msg);
System.err.println("Usage: java " + JMSQueueSink.class.getName() + " QueueConnectionFactoryBindingName QueueBindingName Username Password");
System.exit(1);
}
}

View File

@ -0,0 +1,211 @@
package ch.qos.logback.classic.net;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.net.JMSAppenderBase;
import ch.qos.logback.core.spi.PreSerializationTransformer;
import java.io.Serializable;
import javax.jms.ObjectMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.naming.Context;
public class JMSTopicAppender
extends JMSAppenderBase<ILoggingEvent>
{
static int SUCCESSIVE_FAILURE_LIMIT = 3;
String topicBindingName;
String tcfBindingName;
TopicConnection topicConnection;
TopicSession topicSession;
TopicPublisher topicPublisher;
int successiveFailureCount = 0;
private PreSerializationTransformer<ILoggingEvent> pst = new LoggingEventPreSerializationTransformer();
public JMSTopicAppender() {}
public void setTopicConnectionFactoryBindingName(String tcfBindingName)
{
this.tcfBindingName = tcfBindingName;
}
public String getTopicConnectionFactoryBindingName()
{
return tcfBindingName;
}
public void setTopicBindingName(String topicBindingName)
{
this.topicBindingName = topicBindingName;
}
public String getTopicBindingName()
{
return topicBindingName;
}
public void start()
{
try
{
Context jndi = buildJNDIContext();
TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory)lookup(jndi, tcfBindingName);
if (userName != null) {
topicConnection = topicConnectionFactory.createTopicConnection(userName, password);
}
else {
topicConnection = topicConnectionFactory.createTopicConnection();
}
topicSession = topicConnection.createTopicSession(false, 1);
Topic topic = (Topic)lookup(jndi, topicBindingName);
topicPublisher = topicSession.createPublisher(topic);
topicConnection.start();
jndi.close();
} catch (Exception e) {
addError("Error while activating options for appender named [" + name + "].", e);
}
if ((topicConnection != null) && (topicSession != null) && (topicPublisher != null))
{
super.start();
}
}
public synchronized void stop()
{
if (!started) {
return;
}
started = false;
try
{
if (topicSession != null) {
topicSession.close();
}
if (topicConnection != null) {
topicConnection.close();
}
} catch (Exception e) {
addError("Error while closing JMSAppender [" + name + "].", e);
}
topicPublisher = null;
topicSession = null;
topicConnection = null;
}
public void append(ILoggingEvent event)
{
if (!isStarted()) {
return;
}
try
{
ObjectMessage msg = topicSession.createObjectMessage();
Serializable so = pst.transform(event);
msg.setObject(so);
topicPublisher.publish(msg);
successiveFailureCount = 0;
} catch (Exception e) {
successiveFailureCount += 1;
if (successiveFailureCount > SUCCESSIVE_FAILURE_LIMIT) {
stop();
}
addError("Could not publish message in JMSTopicAppender [" + name + "].", e);
}
}
protected TopicConnection getTopicConnection()
{
return topicConnection;
}
protected TopicSession getTopicSession()
{
return topicSession;
}
protected TopicPublisher getTopicPublisher()
{
return topicPublisher;
}
}

View File

@ -0,0 +1,152 @@
package ch.qos.logback.classic.net;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.util.ContextInitializer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.Properties;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NameNotFoundException;
import javax.naming.NamingException;
import org.slf4j.LoggerFactory;
public class JMSTopicSink
implements MessageListener
{
private Logger logger = (Logger)LoggerFactory.getLogger(JMSTopicSink.class);
public static void main(String[] args) throws Exception {
if (args.length < 2) {
usage("Wrong number of arguments.");
}
String tcfBindingName = args[0];
String topicBindingName = args[1];
String username = null;
String password = null;
if (args.length == 4) {
username = args[2];
password = args[3];
}
LoggerContext loggerContext = (LoggerContext)LoggerFactory.getILoggerFactory();
new ContextInitializer(loggerContext).autoConfig();
new JMSTopicSink(tcfBindingName, topicBindingName, username, password);
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Type \"exit\" to quit JMSTopicSink.");
for (;;) {
String s = stdin.readLine();
if (s.equalsIgnoreCase("exit")) {
System.out.println("Exiting. Kill the application if it does not exit due to daemon threads.");
return;
}
}
}
public JMSTopicSink(String tcfBindingName, String topicBindingName, String username, String password)
{
try
{
Properties env = new Properties();
env.put("java.naming.factory.initial", "org.apache.activemq.jndi.ActiveMQInitialContextFactory");
env.put("java.naming.provider.url", "tcp://localhost:61616");
Context ctx = new InitialContext(env);
TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory)lookup(ctx, tcfBindingName);
System.out.println("Topic Cnx Factory found");
Topic topic = (Topic)ctx.lookup(topicBindingName);
System.out.println("Topic found: " + topic.getTopicName());
TopicConnection topicConnection = topicConnectionFactory.createTopicConnection(username, password);
System.out.println("Topic Connection created");
TopicSession topicSession = topicConnection.createTopicSession(false, 1);
TopicSubscriber topicSubscriber = topicSession.createSubscriber(topic);
topicSubscriber.setMessageListener(this);
topicConnection.start();
System.out.println("Topic Connection started");
}
catch (Exception e) {
logger.error("Could not read JMS message.", e);
}
}
public void onMessage(Message message)
{
try {
if ((message instanceof ObjectMessage)) {
ObjectMessage objectMessage = (ObjectMessage)message;
ILoggingEvent event = (ILoggingEvent)objectMessage.getObject();
Logger log = (Logger)LoggerFactory.getLogger(event.getLoggerName());
log.callAppenders(event);
} else {
logger.warn("Received message is of type " + message.getJMSType() + ", was expecting ObjectMessage.");
}
}
catch (JMSException jmse) {
logger.error("Exception thrown while processing incoming message.", jmse);
}
}
protected Object lookup(Context ctx, String name) throws NamingException
{
try {
return ctx.lookup(name);
} catch (NameNotFoundException e) {
logger.error("Could not find name [" + name + "].");
throw e;
}
}
static void usage(String msg) {
System.err.println(msg);
System.err.println("Usage: java " + JMSTopicSink.class.getName() + " TopicConnectionFactoryBindingName TopicBindingName Username Password");
System.exit(1);
}
}

View File

@ -0,0 +1,37 @@
package ch.qos.logback.classic.net;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.classic.spi.LoggingEventVO;
import ch.qos.logback.core.spi.PreSerializationTransformer;
import java.io.Serializable;
public class LoggingEventPreSerializationTransformer
implements PreSerializationTransformer<ILoggingEvent>
{
public LoggingEventPreSerializationTransformer() {}
public Serializable transform(ILoggingEvent event)
{
if (event == null) {
return null;
}
if ((event instanceof LoggingEvent))
return LoggingEventVO.build(event);
if ((event instanceof LoggingEventVO)) {
return (LoggingEventVO)event;
}
throw new IllegalArgumentException("Unsupported type " + event.getClass().getName());
}
}

View File

@ -0,0 +1,70 @@
package ch.qos.logback.classic.net;
import ch.qos.logback.core.Context;
import ch.qos.logback.core.spi.ContextAwareBase;
import ch.qos.logback.core.spi.LifeCycle;
import java.util.concurrent.ExecutorService;
public abstract class ReceiverBase
extends ContextAwareBase
implements LifeCycle
{
private boolean started;
public ReceiverBase() {}
public final void start()
{
if (isStarted()) return;
if (getContext() == null) {
throw new IllegalStateException("context not set");
}
if (shouldStart()) {
getContext().getExecutorService().execute(getRunnableTask());
started = true;
}
}
public final void stop()
{
if (!isStarted()) return;
try {
onStop();
}
catch (RuntimeException ex) {
addError("on stop: " + ex, ex);
}
started = false;
}
public final boolean isStarted()
{
return started;
}
protected abstract boolean shouldStart();
protected abstract void onStop();
protected abstract Runnable getRunnableTask();
}

View File

@ -0,0 +1,135 @@
package ch.qos.logback.classic.net;
import ch.qos.logback.classic.ClassicConstants;
import ch.qos.logback.classic.PatternLayout;
import ch.qos.logback.classic.boolex.OnErrorEvaluator;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Layout;
import ch.qos.logback.core.boolex.EventEvaluator;
import ch.qos.logback.core.helpers.CyclicBuffer;
import ch.qos.logback.core.net.SMTPAppenderBase;
import org.slf4j.Marker;
public class SMTPAppender
extends SMTPAppenderBase<ILoggingEvent>
{
static final String DEFAULT_SUBJECT_PATTERN = "%logger{20} - %m";
private int bufferSize = 512;
private boolean includeCallerData = false;
public SMTPAppender() {}
public void start()
{
if (eventEvaluator == null) {
OnErrorEvaluator onError = new OnErrorEvaluator();
onError.setContext(getContext());
onError.setName("onError");
onError.start();
eventEvaluator = onError;
}
super.start();
}
public SMTPAppender(EventEvaluator<ILoggingEvent> eventEvaluator)
{
this.eventEvaluator = eventEvaluator;
}
protected void subAppend(CyclicBuffer<ILoggingEvent> cb, ILoggingEvent event)
{
if (includeCallerData) {
event.getCallerData();
}
event.prepareForDeferredProcessing();
cb.add(event);
}
protected void fillBuffer(CyclicBuffer<ILoggingEvent> cb, StringBuffer sbuf)
{
int len = cb.length();
for (int i = 0; i < len; i++) {
ILoggingEvent event = (ILoggingEvent)cb.get();
sbuf.append(layout.doLayout(event));
}
}
protected boolean eventMarksEndOfLife(ILoggingEvent eventObject) {
Marker marker = eventObject.getMarker();
if (marker == null) {
return false;
}
return marker.contains(ClassicConstants.FINALIZE_SESSION_MARKER);
}
protected Layout<ILoggingEvent> makeSubjectLayout(String subjectStr)
{
if (subjectStr == null) {
subjectStr = "%logger{20} - %m";
}
PatternLayout pl = new PatternLayout();
pl.setContext(getContext());
pl.setPattern(subjectStr);
pl.setPostCompileProcessor(null);
pl.start();
return pl;
}
protected PatternLayout makeNewToPatternLayout(String toPattern)
{
PatternLayout pl = new PatternLayout();
pl.setPattern(toPattern + "%nopex");
return pl;
}
public boolean isIncludeCallerData() {
return includeCallerData;
}
public void setIncludeCallerData(boolean includeCallerData) {
this.includeCallerData = includeCallerData;
}
}

View File

@ -0,0 +1,54 @@
package ch.qos.logback.classic.net;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.net.AbstractSSLSocketAppender;
import ch.qos.logback.core.spi.PreSerializationTransformer;
public class SSLSocketAppender
extends AbstractSSLSocketAppender<ILoggingEvent>
{
private final PreSerializationTransformer<ILoggingEvent> pst = new LoggingEventPreSerializationTransformer();
private boolean includeCallerData;
public SSLSocketAppender() {}
protected void postProcessEvent(ILoggingEvent event)
{
if (includeCallerData) {
event.getCallerData();
}
}
public void setIncludeCallerData(boolean includeCallerData) {
this.includeCallerData = includeCallerData;
}
public PreSerializationTransformer<ILoggingEvent> getPST() {
return pst;
}
}

View File

@ -0,0 +1,83 @@
package ch.qos.logback.classic.net;
import ch.qos.logback.core.net.ssl.ConfigurableSSLSocketFactory;
import ch.qos.logback.core.net.ssl.SSLComponent;
import ch.qos.logback.core.net.ssl.SSLConfiguration;
import ch.qos.logback.core.net.ssl.SSLParametersConfiguration;
import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
public class SSLSocketReceiver
extends SocketReceiver
implements SSLComponent
{
private SSLConfiguration ssl;
private SocketFactory socketFactory;
public SSLSocketReceiver() {}
protected SocketFactory getSocketFactory()
{
return socketFactory;
}
protected boolean shouldStart()
{
try
{
SSLContext sslContext = getSsl().createContext(this);
SSLParametersConfiguration parameters = getSsl().getParameters();
parameters.setContext(getContext());
socketFactory = new ConfigurableSSLSocketFactory(parameters, sslContext.getSocketFactory());
return super.shouldStart();
}
catch (Exception ex) {
addError(ex.getMessage(), ex); }
return false;
}
public SSLConfiguration getSsl()
{
if (ssl == null) {
ssl = new SSLConfiguration();
}
return ssl;
}
public void setSsl(SSLConfiguration ssl)
{
this.ssl = ssl;
}
}

View File

@ -0,0 +1,100 @@
package ch.qos.logback.classic.net;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.net.ssl.ConfigurableSSLServerSocketFactory;
import ch.qos.logback.core.net.ssl.SSLParametersConfiguration;
import java.security.NoSuchAlgorithmException;
import javax.net.ServerSocketFactory;
import javax.net.ssl.SSLContext;
public class SimpleSSLSocketServer
extends SimpleSocketServer
{
private final ServerSocketFactory socketFactory;
public static void main(String[] argv)
throws Exception
{
doMain(SimpleSSLSocketServer.class, argv);
}
public SimpleSSLSocketServer(LoggerContext lc, int port)
throws NoSuchAlgorithmException
{
this(lc, port, SSLContext.getDefault());
}
public SimpleSSLSocketServer(LoggerContext lc, int port, SSLContext sslContext)
{
super(lc, port);
if (sslContext == null) {
throw new NullPointerException("SSL context required");
}
SSLParametersConfiguration parameters = new SSLParametersConfiguration();
parameters.setContext(lc);
socketFactory = new ConfigurableSSLServerSocketFactory(parameters, sslContext.getServerSocketFactory());
}
protected ServerSocketFactory getServerSocketFactory()
{
return socketFactory;
}
}

View File

@ -0,0 +1,239 @@
package ch.qos.logback.classic.net;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import javax.net.ServerSocketFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SimpleSocketServer
extends Thread
{
Logger logger = LoggerFactory.getLogger(SimpleSocketServer.class);
private final int port;
private final LoggerContext lc;
private boolean closed = false;
private ServerSocket serverSocket;
private List<SocketNode> socketNodeList = new ArrayList();
private CountDownLatch latch;
public static void main(String[] argv)
throws Exception
{
doMain(SimpleSocketServer.class, argv);
}
protected static void doMain(Class<? extends SimpleSocketServer> serverClass, String[] argv) throws Exception
{
int port = -1;
if (argv.length == 2) {
port = parsePortNumber(argv[0]);
} else {
usage("Wrong number of arguments.");
}
String configFile = argv[1];
LoggerContext lc = (LoggerContext)LoggerFactory.getILoggerFactory();
configureLC(lc, configFile);
SimpleSocketServer sss = new SimpleSocketServer(lc, port);
sss.start();
}
public SimpleSocketServer(LoggerContext lc, int port) {
this.lc = lc;
this.port = port;
}
public void run()
{
String oldThreadName = Thread.currentThread().getName();
try
{
String newThreadName = getServerThreadName();
Thread.currentThread().setName(newThreadName);
logger.info("Listening on port " + port);
serverSocket = getServerSocketFactory().createServerSocket(port);
while (!closed) {
logger.info("Waiting to accept a new client.");
signalAlmostReadiness();
Socket socket = serverSocket.accept();
logger.info("Connected to client at " + socket.getInetAddress());
logger.info("Starting new socket node.");
SocketNode newSocketNode = new SocketNode(this, socket, lc);
synchronized (socketNodeList) {
socketNodeList.add(newSocketNode);
}
String clientThreadName = getClientThreadName(socket);
new Thread(newSocketNode, clientThreadName).start();
}
} catch (Exception e) {
if (closed) {
logger.info("Exception in run method for a closed server. This is normal.");
} else {
logger.error("Unexpected failure in run method", e);
}
}
finally
{
Thread.currentThread().setName(oldThreadName);
}
}
protected String getServerThreadName()
{
return String.format("Logback %s (port %d)", new Object[] { getClass().getSimpleName(), Integer.valueOf(port) });
}
protected String getClientThreadName(Socket socket)
{
return String.format("Logback SocketNode (client: %s)", new Object[] { socket.getRemoteSocketAddress() });
}
protected ServerSocketFactory getServerSocketFactory()
{
return ServerSocketFactory.getDefault();
}
void signalAlmostReadiness()
{
if ((latch != null) && (latch.getCount() != 0L))
{
latch.countDown();
}
}
void setLatch(CountDownLatch latch)
{
this.latch = latch;
}
public CountDownLatch getLatch()
{
return latch;
}
public boolean isClosed() { return closed; }
public void close()
{
closed = true;
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
logger.error("Failed to close serverSocket", e);
} finally {
serverSocket = null;
}
}
logger.info("closing this server");
synchronized (socketNodeList) {
for (SocketNode sn : socketNodeList) {
sn.close();
}
}
if (socketNodeList.size() != 0) {
logger.warn("Was expecting a 0-sized socketNodeList after server shutdown");
}
}
public void socketNodeClosing(SocketNode sn)
{
logger.debug("Removing {}", sn);
synchronized (socketNodeList) {
socketNodeList.remove(sn);
}
}
static void usage(String msg) {
System.err.println(msg);
System.err.println("Usage: java " + SimpleSocketServer.class.getName() + " port configFile");
System.exit(1);
}
static int parsePortNumber(String portStr) {
try {
return Integer.parseInt(portStr);
} catch (NumberFormatException e) {
e.printStackTrace();
usage("Could not interpret port number [" + portStr + "].");
}
return -1;
}
public static void configureLC(LoggerContext lc, String configFile)
throws JoranException
{
JoranConfigurator configurator = new JoranConfigurator();
lc.reset();
configurator.setContext(lc);
configurator.doConfigure(configFile);
}
}

View File

@ -0,0 +1,9 @@
package ch.qos.logback.classic.net;
class SocketAcceptor
extends Thread
{
SocketAcceptor() {}
public void run() {}
}

View File

@ -0,0 +1,59 @@
package ch.qos.logback.classic.net;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.net.AbstractSocketAppender;
import ch.qos.logback.core.spi.PreSerializationTransformer;
public class SocketAppender
extends AbstractSocketAppender<ILoggingEvent>
{
private static final PreSerializationTransformer<ILoggingEvent> pst = new LoggingEventPreSerializationTransformer();
private boolean includeCallerData = false;
public SocketAppender() {}
protected void postProcessEvent(ILoggingEvent event)
{
if (includeCallerData) {
event.getCallerData();
}
}
public void setIncludeCallerData(boolean includeCallerData) {
this.includeCallerData = includeCallerData;
}
public PreSerializationTransformer<ILoggingEvent> getPST() {
return pst;
}
}

View File

@ -0,0 +1,129 @@
package ch.qos.logback.classic.net;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.ILoggingEvent;
import java.io.BufferedInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
public class SocketNode
implements Runnable
{
Socket socket;
LoggerContext context;
ObjectInputStream ois;
SocketAddress remoteSocketAddress;
Logger logger;
boolean closed = false;
SimpleSocketServer socketServer;
public SocketNode(SimpleSocketServer socketServer, Socket socket, LoggerContext context) {
this.socketServer = socketServer;
this.socket = socket;
remoteSocketAddress = socket.getRemoteSocketAddress();
this.context = context;
logger = context.getLogger(SocketNode.class);
}
public void run()
{
try
{
ois = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
}
catch (Exception e) {
logger.error("Could not open ObjectInputStream to " + socket, e);
closed = true;
}
try
{
while (!closed)
{
ILoggingEvent event = (ILoggingEvent)ois.readObject();
Logger remoteLogger = context.getLogger(event.getLoggerName());
if (remoteLogger.isEnabledFor(event.getLevel()))
{
remoteLogger.callAppenders(event);
}
}
} catch (EOFException e) {
logger.info("Caught java.io.EOFException closing connection.");
} catch (SocketException e) {
logger.info("Caught java.net.SocketException closing connection.");
} catch (IOException e) {
logger.info("Caught java.io.IOException: " + e);
logger.info("Closing connection.");
} catch (Exception e) {
logger.error("Unexpected exception. Closing connection.", e);
}
socketServer.socketNodeClosing(this);
close();
}
void close() {
if (closed) {
return;
}
closed = true;
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
logger.warn("Could not close connection.", e);
} finally {
ois = null;
}
}
}
public String toString()
{
return getClass().getName() + remoteSocketAddress.toString();
}
}

View File

@ -0,0 +1,224 @@
package ch.qos.logback.classic.net;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Context;
import ch.qos.logback.core.net.DefaultSocketConnector;
import ch.qos.logback.core.net.SocketConnector;
import ch.qos.logback.core.net.SocketConnector.ExceptionHandler;
import ch.qos.logback.core.util.CloseUtil;
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import javax.net.SocketFactory;
public class SocketReceiver
extends ReceiverBase
implements Runnable, SocketConnector.ExceptionHandler
{
private static final int DEFAULT_ACCEPT_CONNECTION_DELAY = 5000;
private String remoteHost;
private InetAddress address;
private int port;
private int reconnectionDelay;
private int acceptConnectionTimeout = 5000;
private String receiverId;
private volatile Socket socket;
private Future<Socket> connectorTask;
public SocketReceiver() {}
protected boolean shouldStart()
{
int errorCount = 0;
if (port == 0) {
errorCount++;
addError("No port was configured for receiver. For more information, please visit http://logback.qos.ch/codes.html#receiver_no_port");
}
if (remoteHost == null) {
errorCount++;
addError("No host name or address was configured for receiver. For more information, please visit http://logback.qos.ch/codes.html#receiver_no_host");
}
if (reconnectionDelay == 0) {
reconnectionDelay = 30000;
}
if (errorCount == 0) {
try {
address = InetAddress.getByName(remoteHost);
} catch (UnknownHostException ex) {
addError("unknown host: " + remoteHost);
errorCount++;
}
}
if (errorCount == 0) {
receiverId = ("receiver " + remoteHost + ":" + port + ": ");
}
return errorCount == 0;
}
protected void onStop()
{
if (socket != null) {
CloseUtil.closeQuietly(socket);
}
}
protected Runnable getRunnableTask()
{
return this;
}
public void run()
{
try
{
LoggerContext lc = (LoggerContext)getContext();
while (!Thread.currentThread().isInterrupted()) {
SocketConnector connector = createConnector(address, port, 0, reconnectionDelay);
connectorTask = activateConnector(connector);
if (connectorTask == null)
break;
socket = waitForConnectorToReturnASocket();
if (socket == null)
break;
dispatchEvents(lc);
}
}
catch (InterruptedException ex) {}
addInfo("shutting down");
}
private SocketConnector createConnector(InetAddress address, int port, int initialDelay, int retryDelay)
{
SocketConnector connector = newConnector(address, port, initialDelay, retryDelay);
connector.setExceptionHandler(this);
connector.setSocketFactory(getSocketFactory());
return connector;
}
private Future<Socket> activateConnector(SocketConnector connector)
{
try {
return getContext().getExecutorService().submit(connector);
} catch (RejectedExecutionException ex) {}
return null;
}
private Socket waitForConnectorToReturnASocket() throws InterruptedException
{
try {
Socket s = (Socket)connectorTask.get();
connectorTask = null;
return s;
} catch (ExecutionException e) {}
return null;
}
private void dispatchEvents(LoggerContext lc)
{
try {
socket.setSoTimeout(acceptConnectionTimeout);
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
socket.setSoTimeout(0);
addInfo(receiverId + "connection established");
for (;;) {
ILoggingEvent event = (ILoggingEvent)ois.readObject();
Logger remoteLogger = lc.getLogger(event.getLoggerName());
if (remoteLogger.isEnabledFor(event.getLevel())) {
remoteLogger.callAppenders(event);
}
}
} catch (EOFException ex) {
addInfo(receiverId + "end-of-stream detected");
} catch (IOException ex) {
addInfo(receiverId + "connection failed: " + ex);
} catch (ClassNotFoundException ex) {
addInfo(receiverId + "unknown event class: " + ex);
} finally {
CloseUtil.closeQuietly(socket);
socket = null;
addInfo(receiverId + "connection closed");
}
}
public void connectionFailed(SocketConnector connector, Exception ex)
{
if ((ex instanceof InterruptedException)) {
addInfo("connector interrupted");
} else if ((ex instanceof ConnectException)) {
addInfo(receiverId + "connection refused");
} else {
addInfo(receiverId + ex);
}
}
protected SocketConnector newConnector(InetAddress address, int port, int initialDelay, int retryDelay)
{
return new DefaultSocketConnector(address, port, initialDelay, retryDelay);
}
protected SocketFactory getSocketFactory() {
return SocketFactory.getDefault();
}
public void setRemoteHost(String remoteHost) {
this.remoteHost = remoteHost;
}
public void setPort(int port) {
this.port = port;
}
public void setReconnectionDelay(int reconnectionDelay) {
this.reconnectionDelay = reconnectionDelay;
}
public void setAcceptConnectionTimeout(int acceptConnectionTimeout) {
this.acceptConnectionTimeout = acceptConnectionTimeout;
}
}

View File

@ -0,0 +1,183 @@
package ch.qos.logback.classic.net;
import ch.qos.logback.classic.PatternLayout;
import ch.qos.logback.classic.pattern.SyslogStartConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.classic.spi.StackTraceElementProxy;
import ch.qos.logback.classic.util.LevelToSyslogSeverity;
import ch.qos.logback.core.Layout;
import ch.qos.logback.core.net.SyslogAppenderBase;
import ch.qos.logback.core.net.SyslogOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Map;
public class SyslogAppender
extends SyslogAppenderBase<ILoggingEvent>
{
public static final String DEFAULT_SUFFIX_PATTERN = "[%thread] %logger %msg";
public static final String DEFAULT_STACKTRACE_PATTERN = "\t";
PatternLayout stackTraceLayout = new PatternLayout();
String stackTracePattern = "\t";
boolean throwableExcluded = false;
public SyslogAppender() {}
public void start() { super.start();
setupStackTraceLayout();
}
String getPrefixPattern() {
return "%syslogStart{" + getFacility() + "}%nopex{}";
}
public SyslogOutputStream createOutputStream() throws SocketException, UnknownHostException
{
return new SyslogOutputStream(getSyslogHost(), getPort());
}
public int getSeverityForEvent(Object eventObject)
{
ILoggingEvent event = (ILoggingEvent)eventObject;
return LevelToSyslogSeverity.convert(event);
}
protected void postProcess(Object eventObject, OutputStream sw)
{
if (throwableExcluded) {
return;
}
ILoggingEvent event = (ILoggingEvent)eventObject;
IThrowableProxy tp = event.getThrowableProxy();
if (tp == null) {
return;
}
String stackTracePrefix = stackTraceLayout.doLayout(event);
boolean isRootException = true;
while (tp != null) {
StackTraceElementProxy[] stepArray = tp.getStackTraceElementProxyArray();
try {
handleThrowableFirstLine(sw, tp, stackTracePrefix, isRootException);
isRootException = false;
for (StackTraceElementProxy step : stepArray) {
StringBuilder sb = new StringBuilder();
sb.append(stackTracePrefix).append(step);
sw.write(sb.toString().getBytes());
sw.flush();
}
} catch (IOException e) {
break;
}
tp = tp.getCause();
}
}
private void handleThrowableFirstLine(OutputStream sw, IThrowableProxy tp, String stackTracePrefix, boolean isRootException) throws IOException
{
StringBuilder sb = new StringBuilder().append(stackTracePrefix);
if (!isRootException) {
sb.append("Caused by: ");
}
sb.append(tp.getClassName()).append(": ").append(tp.getMessage());
sw.write(sb.toString().getBytes());
sw.flush();
}
boolean stackTraceHeaderLine(StringBuilder sb, boolean topException)
{
return false;
}
public Layout<ILoggingEvent> buildLayout() {
PatternLayout layout = new PatternLayout();
layout.getInstanceConverterMap().put("syslogStart", SyslogStartConverter.class.getName());
if (suffixPattern == null) {
suffixPattern = "[%thread] %logger %msg";
}
layout.setPattern(getPrefixPattern() + suffixPattern);
layout.setContext(getContext());
layout.start();
return layout;
}
private void setupStackTraceLayout() {
stackTraceLayout.getInstanceConverterMap().put("syslogStart", SyslogStartConverter.class.getName());
stackTraceLayout.setPattern(getPrefixPattern() + stackTracePattern);
stackTraceLayout.setContext(getContext());
stackTraceLayout.start();
}
public boolean isThrowableExcluded() {
return throwableExcluded;
}
public void setThrowableExcluded(boolean throwableExcluded)
{
this.throwableExcluded = throwableExcluded;
}
public String getStackTracePattern()
{
return stackTracePattern;
}
public void setStackTracePattern(String stackTracePattern)
{
this.stackTracePattern = stackTracePattern;
}
}

View File

@ -0,0 +1,10 @@
package ch.qos.logback.classic.net.server;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.net.server.Client;
abstract interface RemoteAppenderClient
extends Client
{
public abstract void setLoggerContext(LoggerContext paramLoggerContext);
}

View File

@ -0,0 +1,48 @@
package ch.qos.logback.classic.net.server;
import ch.qos.logback.core.net.server.ServerSocketListener;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
class RemoteAppenderServerListener
extends ServerSocketListener<RemoteAppenderClient>
{
public RemoteAppenderServerListener(ServerSocket serverSocket)
{
super(serverSocket);
}
protected RemoteAppenderClient createClient(String id, Socket socket)
throws IOException
{
return new RemoteAppenderStreamClient(id, socket);
}
}

View File

@ -0,0 +1,52 @@
package ch.qos.logback.classic.net.server;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.net.server.ConcurrentServerRunner;
import ch.qos.logback.core.net.server.ServerListener;
import java.util.concurrent.Executor;
class RemoteAppenderServerRunner
extends ConcurrentServerRunner<RemoteAppenderClient>
{
public RemoteAppenderServerRunner(ServerListener<RemoteAppenderClient> listener, Executor executor)
{
super(listener, executor);
}
protected boolean configureClient(RemoteAppenderClient client)
{
client.setLoggerContext((LoggerContext)getContext());
return true;
}
}

View File

@ -0,0 +1,141 @@
package ch.qos.logback.classic.net.server;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.util.CloseUtil;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.Socket;
class RemoteAppenderStreamClient
implements RemoteAppenderClient
{
private final String id;
private final Socket socket;
private final InputStream inputStream;
private LoggerContext lc;
private Logger logger;
public RemoteAppenderStreamClient(String id, Socket socket)
{
this.id = id;
this.socket = socket;
inputStream = null;
}
public RemoteAppenderStreamClient(String id, InputStream inputStream)
{
this.id = id;
socket = null;
this.inputStream = inputStream;
}
public void setLoggerContext(LoggerContext lc)
{
this.lc = lc;
logger = lc.getLogger(getClass().getPackage().getName());
}
public void close()
{
if (socket == null) return;
CloseUtil.closeQuietly(socket);
}
public void run()
{
logger.info(this + ": connected");
ObjectInputStream ois = null;
try {
ois = createObjectInputStream();
for (;;)
{
ILoggingEvent event = (ILoggingEvent)ois.readObject();
Logger remoteLogger = lc.getLogger(event.getLoggerName());
if (remoteLogger.isEnabledFor(event.getLevel()))
{
remoteLogger.callAppenders(event);
}
}
}
catch (EOFException ex) {}catch (IOException ex)
{
logger.info(this + ": " + ex);
}
catch (ClassNotFoundException ex) {
logger.error(this + ": unknown event class");
}
catch (RuntimeException ex) {
logger.error(this + ": " + ex);
}
finally {
if (ois != null) {
CloseUtil.closeQuietly(ois);
}
close();
logger.info(this + ": connection closed");
}
}
private ObjectInputStream createObjectInputStream() throws IOException {
if (inputStream != null) {
return new ObjectInputStream(inputStream);
}
return new ObjectInputStream(socket.getInputStream());
}
public String toString()
{
return "client " + id;
}
}

View File

@ -0,0 +1,53 @@
package ch.qos.logback.classic.net.server;
import ch.qos.logback.classic.net.LoggingEventPreSerializationTransformer;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.net.server.SSLServerSocketAppenderBase;
import ch.qos.logback.core.spi.PreSerializationTransformer;
public class SSLServerSocketAppender
extends SSLServerSocketAppenderBase<ILoggingEvent>
{
private static final PreSerializationTransformer<ILoggingEvent> pst = new LoggingEventPreSerializationTransformer();
private boolean includeCallerData;
public SSLServerSocketAppender() {}
protected void postProcessEvent(ILoggingEvent event)
{
if (isIncludeCallerData()) {
event.getCallerData();
}
}
protected PreSerializationTransformer<ILoggingEvent> getPST()
{
return pst;
}
public boolean isIncludeCallerData() {
return includeCallerData;
}
public void setIncludeCallerData(boolean includeCallerData) {
this.includeCallerData = includeCallerData;
}
}

View File

@ -0,0 +1,69 @@
package ch.qos.logback.classic.net.server;
import ch.qos.logback.core.net.ssl.ConfigurableSSLServerSocketFactory;
import ch.qos.logback.core.net.ssl.SSLComponent;
import ch.qos.logback.core.net.ssl.SSLConfiguration;
import ch.qos.logback.core.net.ssl.SSLParametersConfiguration;
import javax.net.ServerSocketFactory;
import javax.net.ssl.SSLContext;
public class SSLServerSocketReceiver
extends ServerSocketReceiver
implements SSLComponent
{
private SSLConfiguration ssl;
private ServerSocketFactory socketFactory;
public SSLServerSocketReceiver() {}
protected ServerSocketFactory getServerSocketFactory()
throws Exception
{
if (socketFactory == null) {
SSLContext sslContext = getSsl().createContext(this);
SSLParametersConfiguration parameters = getSsl().getParameters();
parameters.setContext(getContext());
socketFactory = new ConfigurableSSLServerSocketFactory(parameters, sslContext.getServerSocketFactory());
}
return socketFactory;
}
public SSLConfiguration getSsl()
{
if (ssl == null) {
ssl = new SSLConfiguration();
}
return ssl;
}
public void setSsl(SSLConfiguration ssl)
{
this.ssl = ssl;
}
}

View File

@ -0,0 +1,55 @@
package ch.qos.logback.classic.net.server;
import ch.qos.logback.classic.net.LoggingEventPreSerializationTransformer;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.net.server.AbstractServerSocketAppender;
import ch.qos.logback.core.spi.PreSerializationTransformer;
public class ServerSocketAppender
extends AbstractServerSocketAppender<ILoggingEvent>
{
private static final PreSerializationTransformer<ILoggingEvent> pst = new LoggingEventPreSerializationTransformer();
private boolean includeCallerData;
public ServerSocketAppender() {}
protected void postProcessEvent(ILoggingEvent event)
{
if (isIncludeCallerData()) {
event.getCallerData();
}
}
protected PreSerializationTransformer<ILoggingEvent> getPST()
{
return pst;
}
public boolean isIncludeCallerData() {
return includeCallerData;
}
public void setIncludeCallerData(boolean includeCallerData) {
this.includeCallerData = includeCallerData;
}
}

View File

@ -0,0 +1,177 @@
package ch.qos.logback.classic.net.server;
import ch.qos.logback.classic.net.ReceiverBase;
import ch.qos.logback.core.Context;
import ch.qos.logback.core.net.server.ServerListener;
import ch.qos.logback.core.net.server.ServerRunner;
import ch.qos.logback.core.util.CloseUtil;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.UnknownHostException;
import java.util.concurrent.Executor;
import javax.net.ServerSocketFactory;
public class ServerSocketReceiver
extends ReceiverBase
{
public static final int DEFAULT_BACKLOG = 50;
private int port = 4560;
private int backlog = 50;
private String address;
private ServerSocket serverSocket;
private ServerRunner runner;
public ServerSocketReceiver() {}
protected boolean shouldStart()
{
try
{
ServerSocket serverSocket = getServerSocketFactory().createServerSocket(getPort(), getBacklog(), getInetAddress());
ServerListener<RemoteAppenderClient> listener = createServerListener(serverSocket);
runner = createServerRunner(listener, getContext().getExecutorService());
runner.setContext(getContext());
return true;
}
catch (Exception ex) {
addError("server startup error: " + ex, ex);
CloseUtil.closeQuietly(this.serverSocket); }
return false;
}
protected ServerListener<RemoteAppenderClient> createServerListener(ServerSocket socket)
{
return new RemoteAppenderServerListener(socket);
}
protected ServerRunner createServerRunner(ServerListener<RemoteAppenderClient> listener, Executor executor)
{
return new RemoteAppenderServerRunner(listener, executor);
}
protected Runnable getRunnableTask()
{
return runner;
}
protected void onStop()
{
try
{
if (runner == null) return;
runner.stop();
}
catch (IOException ex) {
addError("server shutdown error: " + ex, ex);
}
}
protected ServerSocketFactory getServerSocketFactory()
throws Exception
{
return ServerSocketFactory.getDefault();
}
protected InetAddress getInetAddress()
throws UnknownHostException
{
if (getAddress() == null) return null;
return InetAddress.getByName(getAddress());
}
public int getPort()
{
return port;
}
public void setPort(int port)
{
this.port = port;
}
public int getBacklog()
{
return backlog;
}
public void setBacklog(int backlog)
{
this.backlog = backlog;
}
public String getAddress()
{
return address;
}
public void setAddress(String address)
{
this.address = address;
}
}

View File

@ -0,0 +1,6 @@
package ch.qos.logback.classic.pattern;
public abstract interface Abbreviator
{
public abstract String abbreviate(String paramString);
}

View File

@ -0,0 +1,174 @@
package ch.qos.logback.classic.pattern;
import ch.qos.logback.classic.spi.CallerData;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Context;
import ch.qos.logback.core.CoreConstants;
import ch.qos.logback.core.boolex.EvaluationException;
import ch.qos.logback.core.boolex.EventEvaluator;
import ch.qos.logback.core.status.ErrorStatus;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
public class CallerDataConverter
extends ClassicConverter
{
public static final String DEFAULT_CALLER_LINE_PREFIX = "Caller+";
public static final String DEFAULT_RANGE_DELIMITER = "..";
private int depthStart = 0;
private int depthEnd = 5;
List<EventEvaluator<ILoggingEvent>> evaluatorList = null;
final int MAX_ERROR_COUNT = 4;
int errorCount = 0;
public CallerDataConverter() {}
public void start() { String depthStr = getFirstOption();
if (depthStr == null) {
return;
}
try
{
if (isRange(depthStr)) {
String[] numbers = splitRange(depthStr);
if (numbers.length == 2) {
depthStart = Integer.parseInt(numbers[0]);
depthEnd = Integer.parseInt(numbers[1]);
checkRange();
} else {
addError("Failed to parse depth option as range [" + depthStr + "]");
}
} else {
depthEnd = Integer.parseInt(depthStr);
}
} catch (NumberFormatException nfe) {
addError("Failed to parse depth option [" + depthStr + "]", nfe);
}
List optionList = getOptionList();
if ((optionList != null) && (optionList.size() > 1)) {
int optionListSize = optionList.size();
for (int i = 1; i < optionListSize; i++) {
String evaluatorStr = (String)optionList.get(i);
Context context = getContext();
if (context != null) {
Map evaluatorMap = (Map)context.getObject("EVALUATOR_MAP");
EventEvaluator<ILoggingEvent> ee = (EventEvaluator)evaluatorMap.get(evaluatorStr);
if (ee != null) {
addEvaluator(ee);
}
}
}
}
}
private boolean isRange(String depthStr) {
return depthStr.contains(getDefaultRangeDelimiter());
}
private String[] splitRange(String depthStr) {
return depthStr.split(Pattern.quote(getDefaultRangeDelimiter()), 2);
}
private void checkRange() {
if ((depthStart < 0) || (depthEnd < 0)) {
addError("Invalid depthStart/depthEnd range [" + depthStart + ", " + depthEnd + "] (negative values are not allowed)");
} else if (depthStart >= depthEnd) {
addError("Invalid depthEnd range [" + depthStart + ", " + depthEnd + "] (start greater or equal to end)");
}
}
private void addEvaluator(EventEvaluator<ILoggingEvent> ee) {
if (evaluatorList == null) {
evaluatorList = new ArrayList();
}
evaluatorList.add(ee);
}
public String convert(ILoggingEvent le) {
StringBuilder buf = new StringBuilder();
if (evaluatorList != null) {
boolean printCallerData = false;
for (int i = 0; i < evaluatorList.size(); i++) {
EventEvaluator<ILoggingEvent> ee = (EventEvaluator)evaluatorList.get(i);
try {
if (ee.evaluate(le)) {
printCallerData = true;
break;
}
} catch (EvaluationException eex) {
errorCount += 1;
if (errorCount < 4) {
addError("Exception thrown for evaluator named [" + ee.getName() + "]", eex);
}
else if (errorCount == 4) {
ErrorStatus errorStatus = new ErrorStatus("Exception thrown for evaluator named [" + ee.getName() + "].", this, eex);
errorStatus.add(new ErrorStatus("This was the last warning about this evaluator's errors.We don't want the StatusManager to get flooded.", this));
addStatus(errorStatus);
}
}
}
if (!printCallerData) {
return "";
}
}
StackTraceElement[] cda = le.getCallerData();
if ((cda != null) && (cda.length > depthStart)) {
int limit = depthEnd < cda.length ? depthEnd : cda.length;
for (int i = depthStart; i < limit; i++) {
buf.append(getCallerLinePrefix());
buf.append(i);
buf.append("\t at ");
buf.append(cda[i]);
buf.append(CoreConstants.LINE_SEPARATOR);
}
return buf.toString();
}
return CallerData.CALLER_DATA_NA;
}
protected String getCallerLinePrefix()
{
return "Caller+";
}
protected String getDefaultRangeDelimiter() {
return "..";
}
}

View File

@ -0,0 +1,36 @@
package ch.qos.logback.classic.pattern;
public class ClassNameOnlyAbbreviator
implements Abbreviator
{
public ClassNameOnlyAbbreviator() {}
public String abbreviate(String fqClassName)
{
int lastIndex = fqClassName.lastIndexOf('.');
if (lastIndex != -1) {
return fqClassName.substring(lastIndex + 1, fqClassName.length());
}
return fqClassName;
}
}

View File

@ -0,0 +1,29 @@
package ch.qos.logback.classic.pattern;
import ch.qos.logback.classic.spi.ILoggingEvent;
public class ClassOfCallerConverter
extends NamedConverter
{
public ClassOfCallerConverter() {}
protected String getFullyQualifiedName(ILoggingEvent event)
{
StackTraceElement[] cda = event.getCallerData();
if ((cda != null) && (cda.length > 0)) {
return cda[0].getClassName();
}
return "?";
}
}

View File

@ -0,0 +1,10 @@
package ch.qos.logback.classic.pattern;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.pattern.DynamicConverter;
public abstract class ClassicConverter
extends DynamicConverter<ILoggingEvent>
{
public ClassicConverter() {}
}

View File

@ -0,0 +1,31 @@
package ch.qos.logback.classic.pattern;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.LoggerContextVO;
public class ContextNameConverter
extends ClassicConverter
{
public ContextNameConverter() {}
public String convert(ILoggingEvent event)
{
return event.getLoggerContextVO().getName();
}
}

View File

@ -0,0 +1,65 @@
package ch.qos.logback.classic.pattern;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.util.CachingDateFormatter;
import java.util.List;
import java.util.TimeZone;
public class DateConverter
extends ClassicConverter
{
long lastTimestamp = -1L;
String timestampStrCache = null;
CachingDateFormatter cachingDateFormatter = null;
public DateConverter() {}
public void start() {
String datePattern = getFirstOption();
if (datePattern == null) {
datePattern = "yyyy-MM-dd HH:mm:ss,SSS";
}
if (datePattern.equals("ISO8601")) {
datePattern = "yyyy-MM-dd HH:mm:ss,SSS";
}
try
{
cachingDateFormatter = new CachingDateFormatter(datePattern);
}
catch (IllegalArgumentException e)
{
addWarn("Could not instantiate SimpleDateFormat with pattern " + datePattern, e);
cachingDateFormatter = new CachingDateFormatter("yyyy-MM-dd HH:mm:ss,SSS");
}
List optionList = getOptionList();
if ((optionList != null) && (optionList.size() > 1)) {
TimeZone tz = TimeZone.getTimeZone((String)optionList.get(1));
cachingDateFormatter.setTimeZone(tz);
}
}
public String convert(ILoggingEvent le) {
long timestamp = le.getTimeStamp();
return cachingDateFormatter.format(timestamp);
}
}

View File

@ -0,0 +1,69 @@
package ch.qos.logback.classic.pattern;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.pattern.Converter;
import ch.qos.logback.core.pattern.ConverterUtil;
import ch.qos.logback.core.pattern.PostCompileProcessor;
public class EnsureExceptionHandling
implements PostCompileProcessor<ILoggingEvent>
{
public EnsureExceptionHandling() {}
public void process(Converter<ILoggingEvent> head)
{
if (head == null)
{
throw new IllegalArgumentException("cannot process empty chain");
}
if (!chainHandlesThrowable(head)) {
Converter<ILoggingEvent> tail = ConverterUtil.findTail(head);
Converter<ILoggingEvent> exConverter = new ExtendedThrowableProxyConverter();
tail.setNext(exConverter);
}
}
public boolean chainHandlesThrowable(Converter head)
{
Converter c = head;
while (c != null) {
if ((c instanceof ThrowableHandlingConverter)) {
return true;
}
c = c.getNext();
}
return false;
}
}

View File

@ -0,0 +1,28 @@
package ch.qos.logback.classic.pattern;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.StackTraceElementProxy;
import ch.qos.logback.classic.spi.ThrowableProxyUtil;
public class ExtendedThrowableProxyConverter
extends ThrowableProxyConverter
{
public ExtendedThrowableProxyConverter() {}
protected void extraData(StringBuilder builder, StackTraceElementProxy step)
{
ThrowableProxyUtil.subjoinPackagingData(builder, step);
}
protected void prepareLoggingEvent(ILoggingEvent event) {}
}

View File

@ -0,0 +1,28 @@
package ch.qos.logback.classic.pattern;
import ch.qos.logback.classic.spi.ILoggingEvent;
public class FileOfCallerConverter
extends ClassicConverter
{
public FileOfCallerConverter() {}
public String convert(ILoggingEvent le)
{
StackTraceElement[] cda = le.getCallerData();
if ((cda != null) && (cda.length > 0)) {
return cda[0].getFileName();
}
return "?";
}
}

View File

@ -0,0 +1,28 @@
package ch.qos.logback.classic.pattern;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
public class LevelConverter
extends ClassicConverter
{
public LevelConverter() {}
public String convert(ILoggingEvent le)
{
return le.getLevel().toString();
}
}

View File

@ -0,0 +1,28 @@
package ch.qos.logback.classic.pattern;
import ch.qos.logback.classic.spi.ILoggingEvent;
public class LineOfCallerConverter
extends ClassicConverter
{
public LineOfCallerConverter() {}
public String convert(ILoggingEvent le)
{
StackTraceElement[] cda = le.getCallerData();
if ((cda != null) && (cda.length > 0)) {
return Integer.toString(cda[0].getLineNumber());
}
return "?";
}
}

View File

@ -0,0 +1,24 @@
package ch.qos.logback.classic.pattern;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.CoreConstants;
public class LineSeparatorConverter
extends ClassicConverter
{
public LineSeparatorConverter() {}
public String convert(ILoggingEvent event)
{
return CoreConstants.LINE_SEPARATOR;
}
}

View File

@ -0,0 +1,35 @@
package ch.qos.logback.classic.pattern;
import ch.qos.logback.classic.spi.ILoggingEvent;
import java.util.concurrent.atomic.AtomicLong;
public class LocalSequenceNumberConverter
extends ClassicConverter
{
AtomicLong sequenceNumber = new AtomicLong(System.currentTimeMillis());
public LocalSequenceNumberConverter() {}
public String convert(ILoggingEvent event) { return Long.toString(sequenceNumber.getAndIncrement()); }
}

View File

@ -0,0 +1,23 @@
package ch.qos.logback.classic.pattern;
import ch.qos.logback.classic.spi.ILoggingEvent;
public class LoggerConverter
extends NamedConverter
{
public LoggerConverter() {}
protected String getFullyQualifiedName(ILoggingEvent event)
{
return event.getLoggerName();
}
}

View File

@ -0,0 +1,81 @@
package ch.qos.logback.classic.pattern;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.util.OptionHelper;
import java.util.Map;
import java.util.Map.Entry;
public class MDCConverter
extends ClassicConverter
{
private String key;
private String defaultValue = "";
public MDCConverter() {}
public void start() { String[] keyInfo = OptionHelper.extractDefaultReplacement(getFirstOption());
key = keyInfo[0];
if (keyInfo[1] != null) {
defaultValue = keyInfo[1];
}
super.start();
}
public void stop()
{
key = null;
super.stop();
}
public String convert(ILoggingEvent event)
{
Map<String, String> mdcPropertyMap = event.getMDCPropertyMap();
if (mdcPropertyMap == null) {
return defaultValue;
}
if (key == null) {
return outputMDCForAllKeys(mdcPropertyMap);
}
String value = (String)event.getMDCPropertyMap().get(key);
if (value != null) {
return value;
}
return defaultValue;
}
private String outputMDCForAllKeys(Map<String, String> mdcPropertyMap)
{
StringBuilder buf = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : mdcPropertyMap.entrySet()) {
if (first) {
first = false;
} else {
buf.append(", ");
}
buf.append((String)entry.getKey()).append('=').append((String)entry.getValue());
}
return buf.toString();
}
}

View File

@ -0,0 +1,36 @@
package ch.qos.logback.classic.pattern;
import ch.qos.logback.classic.spi.ILoggingEvent;
import org.slf4j.Marker;
public class MarkerConverter
extends ClassicConverter
{
public MarkerConverter() {}
private static String EMPTY = "";
public String convert(ILoggingEvent le) {
Marker marker = le.getMarker();
if (marker == null) {
return EMPTY;
}
return marker.toString();
}
}

View File

@ -0,0 +1,28 @@
package ch.qos.logback.classic.pattern;
import ch.qos.logback.classic.spi.ILoggingEvent;
public class MessageConverter
extends ClassicConverter
{
public MessageConverter() {}
public String convert(ILoggingEvent event)
{
return event.getFormattedMessage();
}
}

Some files were not shown because too many files have changed in this diff Show More