478372 - JavaUtilLog setSourceClass and setSourceMethod

Added some additional features to configure the java.util.logging mechansim
This commit is contained in:
Greg Wilkins 2015-09-25 14:08:31 +10:00
parent dcb4c0d0a8
commit 007ac4a9dd
9 changed files with 258 additions and 170 deletions

View File

@ -0,0 +1,9 @@
# Logging
handlers = java.util.logging.ConsoleHandler
.level = INFO
java.util.logging.SimpleFormatter.format=%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$-6s %2$s %5$s%6$s%n
# Console Logging
java.util.logging.ConsoleHandler.level = ALL

View File

@ -1,9 +1,9 @@
org.eclipse.jetty.util.log.class=org.eclipse.jetty.util.log.StdErrLog
org.eclipse.jetty.util.log.class=org.eclipse.jetty.util.log.JavaUtilLog
org.eclipse.jetty.util.log.javautil.PROPERTIES=java-util-logging.properties
#org.eclipse.jetty.util.log.SOURCE=true
org.eclipse.jetty.LEVEL=DEBUG
org.eclipse.jetty.LEVEL=INFO
org.eclipse.jetty.STACKS=true
#org.eclipse.jetty.STACKS=false
#org.eclipse.jetty.server.LEVEL=DEBUG
#org.eclipse.jetty.io.LEVEL=DEBUG
#org.eclipse.jetty.io.ssl.LEVEL=DEBUG
#org.eclipse.jetty.server.LEVEL=DEBUG

View File

@ -47,6 +47,7 @@ import org.eclipse.jetty.http.HttpParser;
import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.server.handler.ErrorHandler;
import org.eclipse.jetty.util.log.AbstractLogger;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.log.StdErrLog;
@ -764,7 +765,7 @@ public class HttpConnectionTest
try
{
((StdErrLog)Log.getLogger(HttpChannel.class)).info("Excpect IOException: Response header too large...");
((AbstractLogger)Log.getLogger(HttpChannel.class)).info("Excpect IOException: Response header too large...");
((StdErrLog)Log.getLogger(HttpChannel.class)).setHideStacks(true);
int offset = 0;

View File

@ -54,6 +54,7 @@ import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.toolchain.test.AdvancedRunner;
import org.eclipse.jetty.toolchain.test.annotation.Slow;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.log.AbstractLogger;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.StdErrLog;
import org.hamcrest.Matchers;
@ -187,7 +188,7 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture
{
client.setSoTimeout(10000);
((StdErrLog)Log.getLogger(HttpConnection.class)).setHideStacks(true);
((StdErrLog) Log.getLogger(HttpConnection.class)).info("expect request is too large, then ISE extra data ...");
((AbstractLogger) Log.getLogger(HttpConnection.class)).info("expect request is too large, then ISE extra data ...");
OutputStream os = client.getOutputStream();
byte[] buffer = new byte[64 * 1024];
@ -218,7 +219,7 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture
try (Socket client = newSocket(_serverURI.getHost(), _serverURI.getPort()))
{
((StdErrLog)Log.getLogger(HttpConnection.class)).setHideStacks(true);
((StdErrLog)Log.getLogger(HttpConnection.class)).info("expect URI is too large, then ISE extra data ...");
((AbstractLogger)Log.getLogger(HttpConnection.class)).info("expect URI is too large, then ISE extra data ...");
OutputStream os = client.getOutputStream();
byte[] buffer = new byte[64 * 1024];
@ -338,7 +339,7 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture
try (Socket client = newSocket(_serverURI.getHost(), _serverURI.getPort()))
{
((StdErrLog)Log.getLogger(HttpConnection.class)).setHideStacks(true);
((StdErrLog)Log.getLogger(HttpConnection.class)).info("expect header is too large, then ISE extra data ...");
((AbstractLogger)Log.getLogger(HttpConnection.class)).info("expect header is too large, then ISE extra data ...");
OutputStream os = client.getOutputStream();
byte[] buffer = new byte[64 * 1024];
@ -1180,7 +1181,7 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture
try
{
((StdErrLog)Log.getLogger(HttpChannel.class)).setHideStacks(true);
((StdErrLog)Log.getLogger(HttpChannel.class)).info("Expecting exception after commit then could not send 500....");
((AbstractLogger)Log.getLogger(HttpChannel.class)).info("Expecting exception after commit then could not send 500....");
OutputStream os = client.getOutputStream();
InputStream is = client.getInputStream();

View File

@ -18,6 +18,7 @@
package org.eclipse.jetty.util.log;
import java.util.Properties;
/* ------------------------------------------------------------ */
/** Abstract Logger.
@ -25,6 +26,13 @@ package org.eclipse.jetty.util.log;
*/
public abstract class AbstractLogger implements Logger
{
public static final int LEVEL_DEFAULT = -1;
public static final int LEVEL_ALL = 0;
public static final int LEVEL_DEBUG = 1;
public static final int LEVEL_INFO = 2;
public static final int LEVEL_WARN = 3;
public static final int LEVEL_OFF = 10;
@Override
public final Logger getLogger(String name)
{
@ -76,6 +84,137 @@ public abstract class AbstractLogger implements Logger
return true;
}
/**
* Get the Logging Level for the provided log name. Using the FQCN first, then each package segment from longest to
* shortest.
*
* @param props
* the properties to check
* @param name
* the name to get log for
* @return the logging level
*/
public static int lookupLoggingLevel(Properties props, final String name)
{
if ((props == null) || (props.isEmpty()) || name==null )
return LEVEL_DEFAULT;
// Calculate the level this named logger should operate under.
// Checking with FQCN first, then each package segment from longest to shortest.
String nameSegment = name;
while ((nameSegment != null) && (nameSegment.length() > 0))
{
String levelStr = props.getProperty(nameSegment + ".LEVEL");
// System.err.printf("[StdErrLog.CONFIG] Checking for property [%s.LEVEL] = %s%n",nameSegment,levelStr);
int level = getLevelId(nameSegment + ".LEVEL",levelStr);
if (level != (-1))
{
return level;
}
// Trim and try again.
int idx = nameSegment.lastIndexOf('.');
if (idx >= 0)
{
nameSegment = nameSegment.substring(0,idx);
}
else
{
nameSegment = null;
}
}
// Default Logging Level
return LEVEL_DEFAULT;
}
public static String getLoggingProperty(Properties props, String name, String property)
{
// Calculate the level this named logger should operate under.
// Checking with FQCN first, then each package segment from longest to shortest.
String nameSegment = name;
while ((nameSegment != null) && (nameSegment.length() > 0))
{
String s = props.getProperty(nameSegment+"."+property);
if (s!=null)
return s;
// Trim and try again.
int idx = nameSegment.lastIndexOf('.');
nameSegment = (idx >= 0)?nameSegment.substring(0,idx):null;
}
return null;
}
protected static int getLevelId(String levelSegment, String levelName)
{
if (levelName == null)
{
return -1;
}
String levelStr = levelName.trim();
if ("ALL".equalsIgnoreCase(levelStr))
{
return LEVEL_ALL;
}
else if ("DEBUG".equalsIgnoreCase(levelStr))
{
return LEVEL_DEBUG;
}
else if ("INFO".equalsIgnoreCase(levelStr))
{
return LEVEL_INFO;
}
else if ("WARN".equalsIgnoreCase(levelStr))
{
return LEVEL_WARN;
}
else if ("OFF".equalsIgnoreCase(levelStr))
{
return LEVEL_OFF;
}
System.err.println("Unknown StdErrLog level [" + levelSegment + "]=[" + levelStr + "], expecting only [ALL, DEBUG, INFO, WARN, OFF] as values.");
return -1;
}
/**
* Condenses a classname by stripping down the package name to just the first character of each package name
* segment.Configured
*
* <pre>
* Examples:
* "org.eclipse.jetty.test.FooTest" = "oejt.FooTest"
* "org.eclipse.jetty.server.logging.LogTest" = "orjsl.LogTest"
* </pre>
*
* @param classname
* the fully qualified class name
* @return the condensed name
*/
protected static String condensePackageString(String classname)
{
String parts[] = classname.split("\\.");
StringBuilder dense = new StringBuilder();
for (int i = 0; i < (parts.length - 1); i++)
{
dense.append(parts[i].charAt(0));
}
if (dense.length() > 0)
{
dense.append('.');
}
dense.append(parts[parts.length - 1]);
return dense.toString();
}
public void debug(String msg, long arg)
{
if (isDebugEnabled())

View File

@ -18,9 +18,15 @@
package org.eclipse.jetty.util.log;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.LogRecord;
import org.eclipse.jetty.util.Loader;
/**
* <p>
* Implementation of Jetty {@link Logger} based on {@link java.util.logging.Logger}.
@ -33,6 +39,18 @@ import java.util.logging.LogRecord;
*
* Configuration Properties:
* <dl>
* <dt>${name|hierarchy}.LEVEL=(ALL|DEBUG|INFO|WARN|OFF)</dt>
* <dd>
* Sets the level that the Logger should log at.<br>
* Names can be a package name, or a fully qualified class name.<br>
* Default: The default from the java.util.logging mechanism/configuration
* <br>
* <dt>org.eclipse.jetty.util.log.javautil.PROPERTIES=&lt;property-resource-name&gt;</dt>
* <dd>If set, it is used as a classpath resource name to find a java.util.logging
* property file.
* <br>
* Default: null
* </dd>
* <dt>org.eclipse.jetty.util.log.javautil.SOURCE=(true|false)</dt>
* <dd>Set the LogRecord source class and method for JavaUtilLog.<br>
* Default: true
@ -50,22 +68,73 @@ public class JavaUtilLog extends AbstractLogger
Boolean.parseBoolean(Log.__props.getProperty("org.eclipse.jetty.util.log.SOURCE",
Log.__props.getProperty("org.eclipse.jetty.util.log.javautil.SOURCE","true")));
private static boolean _initialized=false;
private Level configuredLevel;
private java.util.logging.Logger _logger;
public JavaUtilLog()
{
this("org.eclipse.jetty.util.log");
this("org.eclipse.jetty.util.log.javautil");
}
public JavaUtilLog(String name)
{
_logger = java.util.logging.Logger.getLogger(name);
if (Boolean.parseBoolean(Log.__props.getProperty("org.eclipse.jetty.util.log.DEBUG", "false")))
synchronized (JavaUtilLog.class)
{
_logger.setLevel(Level.FINE);
}
if (!_initialized)
{
_initialized=true;
final String properties=Log.__props.getProperty("org.eclipse.jetty.util.log.javautil.PROPERTIES",null);
if (properties!=null)
{
AccessController.doPrivileged(new PrivilegedAction<Object>()
{
public Object run()
{
try
{
URL props = Loader.getResource(JavaUtilLog.class,properties);
if (props != null)
LogManager.getLogManager().readConfiguration(props.openStream());
}
catch(Throwable e)
{
System.err.println("[WARN] Error loading logging config: " + properties);
e.printStackTrace(System.err);
}
return null;
}
});
}
}
}
_logger = java.util.logging.Logger.getLogger(name);
switch(lookupLoggingLevel(Log.__props,name))
{
case LEVEL_ALL:
_logger.setLevel(Level.ALL);
break;
case LEVEL_DEBUG:
_logger.setLevel(Level.FINE);
break;
case LEVEL_INFO:
_logger.setLevel(Level.INFO);
break;
case LEVEL_WARN:
_logger.setLevel(Level.WARNING);
break;
case LEVEL_OFF:
_logger.setLevel(Level.OFF);
break;
case LEVEL_DEFAULT:
default:
break;
}
configuredLevel = _logger.getLevel();
}

View File

@ -130,7 +130,7 @@ public class Log
});
}
private static void loadProperties(String resourceName, Properties props)
static void loadProperties(String resourceName, Properties props)
{
URL testProps = Loader.getResource(Log.class,resourceName);
if (testProps != null)

View File

@ -21,6 +21,7 @@ package org.eclipse.jetty.util.log;
import java.io.PrintStream;
import java.security.AccessControlException;
import java.util.Properties;
import java.util.logging.Level;
import org.eclipse.jetty.util.DateCache;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
@ -96,19 +97,14 @@ public class StdErrLog extends AbstractLogger
// Do not change output format lightly, people rely on this output format now.
private static int __tagpad = Integer.parseInt(Log.__props.getProperty("org.eclipse.jetty.util.log.StdErrLog.TAG_PAD","0"));
private static DateCache _dateCache;
private static final Properties __props = new Properties();
private final static boolean __source = Boolean.parseBoolean(Log.__props.getProperty("org.eclipse.jetty.util.log.SOURCE",
Log.__props.getProperty("org.eclipse.jetty.util.log.stderr.SOURCE","false")));
private final static boolean __long = Boolean.parseBoolean(Log.__props.getProperty("org.eclipse.jetty.util.log.stderr.LONG","false"));
private final static boolean __escape = Boolean.parseBoolean(Log.__props.getProperty("org.eclipse.jetty.util.log.stderr.ESCAPE","true"));
static
{
__props.putAll(Log.__props);
String deprecatedProperties[] =
{ "DEBUG", "org.eclipse.jetty.util.log.DEBUG", "org.eclipse.jetty.util.log.stderr.DEBUG" };
@ -136,11 +132,6 @@ public class StdErrLog extends AbstractLogger
__tagpad=pad;
}
public static final int LEVEL_ALL = 0;
public static final int LEVEL_DEBUG = 1;
public static final int LEVEL_INFO = 2;
public static final int LEVEL_WARN = 3;
public static final int LEVEL_OFF = 10;
private int _level = LEVEL_INFO;
// Level that this Logger was configured as (remembered in special case of .setDebugEnabled())
@ -155,6 +146,20 @@ public class StdErrLog extends AbstractLogger
private final String _abbrevname;
private boolean _hideStacks = false;
public static int getLoggingLevel(Properties props,String name)
{
int level = lookupLoggingLevel(props,name);
if (level==LEVEL_DEFAULT)
{
level = lookupLoggingLevel(props,"log");
if (level==LEVEL_DEFAULT)
level=LEVEL_INFO;
}
return level;
}
/**
* Obtain a StdErrLog reference for the specified class, a convenience method used most often during testing to allow for control over a specific logger.
* <p>
@ -194,7 +199,7 @@ public class StdErrLog extends AbstractLogger
*/
public StdErrLog(String name)
{
this(name,__props);
this(name,null);
}
/**
@ -207,16 +212,16 @@ public class StdErrLog extends AbstractLogger
*/
public StdErrLog(String name, Properties props)
{
if (props!=null && props!=__props)
__props.putAll(props);
this._name = name == null?"":name;
this._abbrevname = condensePackageString(this._name);
this._level = getLoggingLevel(props,this._name);
this._configuredLevel = this._level;
if (props!=null && props!=Log.__props)
Log.__props.putAll(props);
_name = name == null?"":name;
_abbrevname = condensePackageString(this._name);
_level = getLoggingLevel(Log.__props,this._name);
_configuredLevel = _level;
try
{
String source = getLoggingProperty(props,_name,"SOURCE");
String source = getLoggingProperty(Log.__props,_name,"SOURCE");
_source = source==null?__source:Boolean.parseBoolean(source);
}
catch (AccessControlException ace)
@ -227,7 +232,7 @@ public class StdErrLog extends AbstractLogger
try
{
// allow stacktrace display to be controlled by properties as well
String stacks = getLoggingProperty(props,_name,"STACKS");
String stacks = getLoggingProperty(Log.__props,_name,"STACKS");
_hideStacks = stacks==null?false:!Boolean.parseBoolean(stacks);
}
catch (AccessControlException ignore)
@ -236,136 +241,6 @@ public class StdErrLog extends AbstractLogger
}
}
/**
* Get the Logging Level for the provided log name. Using the FQCN first, then each package segment from longest to
* shortest.
*
* @param props
* the properties to check
* @param name
* the name to get log for
* @return the logging level
*/
public static int getLoggingLevel(Properties props, final String name)
{
if ((props == null) || (props.isEmpty()))
{
// Default Logging Level
return getLevelId("log.LEVEL","INFO");
}
// Calculate the level this named logger should operate under.
// Checking with FQCN first, then each package segment from longest to shortest.
String nameSegment = name;
while ((nameSegment != null) && (nameSegment.length() > 0))
{
String levelStr = props.getProperty(nameSegment + ".LEVEL");
// System.err.printf("[StdErrLog.CONFIG] Checking for property [%s.LEVEL] = %s%n",nameSegment,levelStr);
int level = getLevelId(nameSegment + ".LEVEL",levelStr);
if (level != (-1))
{
return level;
}
// Trim and try again.
int idx = nameSegment.lastIndexOf('.');
if (idx >= 0)
{
nameSegment = nameSegment.substring(0,idx);
}
else
{
nameSegment = null;
}
}
// Default Logging Level
return getLevelId("log.LEVEL",props.getProperty("log.LEVEL","INFO"));
}
public static String getLoggingProperty(Properties props, String name, String property)
{
// Calculate the level this named logger should operate under.
// Checking with FQCN first, then each package segment from longest to shortest.
String nameSegment = name;
while ((nameSegment != null) && (nameSegment.length() > 0))
{
String s = props.getProperty(nameSegment+"."+property);
if (s!=null)
return s;
// Trim and try again.
int idx = nameSegment.lastIndexOf('.');
nameSegment = (idx >= 0)?nameSegment.substring(0,idx):null;
}
return null;
}
protected static int getLevelId(String levelSegment, String levelName)
{
if (levelName == null)
{
return -1;
}
String levelStr = levelName.trim();
if ("ALL".equalsIgnoreCase(levelStr))
{
return LEVEL_ALL;
}
else if ("DEBUG".equalsIgnoreCase(levelStr))
{
return LEVEL_DEBUG;
}
else if ("INFO".equalsIgnoreCase(levelStr))
{
return LEVEL_INFO;
}
else if ("WARN".equalsIgnoreCase(levelStr))
{
return LEVEL_WARN;
}
else if ("OFF".equalsIgnoreCase(levelStr))
{
return LEVEL_OFF;
}
System.err.println("Unknown StdErrLog level [" + levelSegment + "]=[" + levelStr + "], expecting only [ALL, DEBUG, INFO, WARN, OFF] as values.");
return -1;
}
/**
* Condenses a classname by stripping down the package name to just the first character of each package name
* segment.Configured
*
* <pre>
* Examples:
* "org.eclipse.jetty.test.FooTest" = "oejt.FooTest"
* "org.eclipse.jetty.server.logging.LogTest" = "orjsl.LogTest"
* </pre>
*
* @param classname
* the fully qualified class name
* @return the condensed name
*/
protected static String condensePackageString(String classname)
{
String parts[] = classname.split("\\.");
StringBuilder dense = new StringBuilder();
for (int i = 0; i < (parts.length - 1); i++)
{
dense.append(parts[i].charAt(0));
}
if (dense.length() > 0)
{
dense.append('.');
}
dense.append(parts[parts.length - 1]);
return dense.toString();
}
public String getName()
{
return _name;
@ -798,12 +673,6 @@ public class StdErrLog extends AbstractLogger
return s.toString();
}
public static void setProperties(Properties props)
{
__props.clear();
__props.putAll(props);
}
public void ignore(Throwable ignored)
{
if (_level <= LEVEL_ALL)

View File

@ -616,7 +616,7 @@ public class StdErrLogTest
@Test
public void testGetChildLogger_NullParent()
{
StdErrLog log = new StdErrLog(null,new Properties());
AbstractLogger log = new StdErrLog(null,new Properties());
Assert.assertThat("Logger.name", log.getName(), is(""));