Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  //
  //  ========================================================================
  //  Copyright (c) 1995-2013 Mort Bay Consulting Pty. Ltd.
  //  ------------------------------------------------------------------------
  //  All rights reserved. This program and the accompanying materials
  //  are made available under the terms of the Eclipse Public License v1.0
  //  and Apache License v2.0 which accompanies this distribution.
  //
  //      The Eclipse Public License is available at
 //      http://www.eclipse.org/legal/epl-v10.html
 //
 //      The Apache License v2.0 is available at
 //      http://www.opensource.org/licenses/apache2.0.php
 //
 //  You may elect to redistribute this code under either of these licenses.
 //  ========================================================================
 //
 
 package org.eclipse.jetty.util.log;
 
 
StdErr Logging. This implementation of the Logging facade sends all logs to StdErr with minimal formatting.

If the system property "org.eclipse.jetty.LEVEL" is set to one of the following (ALL, DEBUG, INFO, WARN), then set the eclipse jetty root level logger level to that specified level. (Default level is INFO)

If the system property "org.eclipse.jetty.util.log.SOURCE" is set, then the source method/file of a log is logged. For named debuggers, the system property name+".SOURCE" is checked, eg "org.eclipse.jetty.util.log.stderr.SOURCE". If it is not not set, then "org.eclipse.jetty.util.log.SOURCE" is used as the default.

If the system property "org.eclipse.jetty.util.log.stderr.LONG" is set, then the full, unabbreviated name of the logger is used for logging.

 
 public class StdErrLog extends AbstractLogger
 {
     private static final String EOL = System.getProperty("line.separator");
     private static DateCache _dateCache;
     private static final Properties __props = new Properties();
 
     private final static boolean __source = Boolean.parseBoolean(..getProperty("org.eclipse.jetty.util.log.SOURCE",
             ..getProperty("org.eclipse.jetty.util.log.stderr.SOURCE","false")));
     private final static boolean __long = Boolean.parseBoolean(..getProperty("org.eclipse.jetty.util.log.stderr.LONG","false"));
 
     static
     {
         .putAll(.);
         
         String deprecatedProperties[] =
         { "DEBUG""org.eclipse.jetty.util.log.DEBUG""org.eclipse.jetty.util.log.stderr.DEBUG" };
 
         // Toss a message to users about deprecated system properties
         for (String deprecatedProp : deprecatedProperties)
         {
             if (System.getProperty(deprecatedProp) != null)
             {
                 ..printf("System Property [%s] has been deprecated! (Use org.eclipse.jetty.LEVEL=DEBUG instead)%n",deprecatedProp);
             }
         }
 
         try
         {
              = new DateCache("yyyy-MM-dd HH:mm:ss");
         }
         catch (Exception x)
         {
             x.printStackTrace(.);
         }
     }
 
     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;
 
     private int _level = ;
     // Level that this Logger was configured as (remembered in special case of .setDebugEnabled())
     private int _configuredLevel;
     private PrintStream _stderr = null;
     private boolean _source = ;
     // Print the long form names, otherwise use abbreviated
     private boolean _printLongNames = ;
     // The full log name, as provided by the system.
     private final String _name;
     // The abbreviated log name (used by default, unless _long is specified)
     private final String _abbrevname;
     private boolean _hideStacks = false;
 
     public StdErrLog()
     {
         this(null);
     }
 
     public StdErrLog(String name)
    {
        this(name,);
    }
    public StdErrLog(String nameProperties props)
    {
        if (props!=null && props!=)
            .putAll(props);
        this. = name == null?"":name;
        this. = condensePackageString(this.);
        this. = getLoggingLevel(props,this.);
        this. = this.;
        try
        {
             = Boolean.parseBoolean(props.getProperty( + ".SOURCE",Boolean.toString()));
        }
        catch (AccessControlException ace)
        {
             = ;
        }
    }

    
Get the Logging Level for the provided log name. Using the FQCN first, then each package segment from longest to shortest.

Parameters:
props the properties to check
name the name to get log for
Returns:
the logging level
    public static int getLoggingLevel(Properties propsfinal String name)
    {
        // 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"));
    }
    protected static int getLevelId(String levelSegmentString levelName)
    {
        if (levelName == null)
        {
            return -1;
        }
        String levelStr = levelName.trim();
        if ("ALL".equalsIgnoreCase(levelStr))
        {
            return ;
        }
        else if ("DEBUG".equalsIgnoreCase(levelStr))
        {
            return ;
        }
        else if ("INFO".equalsIgnoreCase(levelStr))
        {
            return ;
        }
        else if ("WARN".equalsIgnoreCase(levelStr))
        {
            return ;
        }
        ..println("Unknown StdErrLog level [" + levelSegment + "]=[" + levelStr + "], expecting only [ALL, DEBUG, INFO, WARN] as values.");
        return -1;
    }

    
Condenses a classname by stripping down the package name to just the first character of each package name segment.Configured

 Examples:
 "org.eclipse.jetty.test.FooTest"           = "oejt.FooTest"
 "org.eclipse.jetty.server.logging.LogTest" = "orjsl.LogTest"
 

Parameters:
classname the fully qualified class name
Returns:
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 ;
    }
    public void setPrintLongNames(boolean printLongNames)
    {
        this. = printLongNames;
    }
    public boolean isPrintLongNames()
    {
        return this.;
    }
    public boolean isHideStacks()
    {
        return ;
    }
    public void setHideStacks(boolean hideStacks)
    {
         = hideStacks;
    }
    /* ------------------------------------------------------------ */
    
Is the source of a log, logged

Returns:
true if the class, method, file and line number of a log is logged.
    public boolean isSource()
    {
        return ;
    }
    /* ------------------------------------------------------------ */
    
Set if a log source is logged.

Parameters:
source true if the class, method, file and line number of a log is logged.
    public void setSource(boolean source)
    {
         = source;
    }
    public void warn(String msgObject... args)
    {
        if ( <= )
        {
            StringBuilder buffer = new StringBuilder(64);
            format(buffer,":WARN:",msg,args);
            (==null?.:).println(buffer);
        }
    }
    public void warn(Throwable thrown)
    {
        warn("",thrown);
    }
    public void warn(String msgThrowable thrown)
    {
        if ( <= )
        {
            StringBuilder buffer = new StringBuilder(64);
            format(buffer,":WARN:",msg,thrown);
            (==null?.:).println(buffer);
        }
    }
    public void info(String msgObject... args)
    {
        if ( <= )
        {
            StringBuilder buffer = new StringBuilder(64);
            format(buffer,":INFO:",msg,args);
            (==null?.:).println(buffer);
        }
    }
    public void info(Throwable thrown)
    {
        info("",thrown);
    }
    public void info(String msgThrowable thrown)
    {
        if ( <= )
        {
            StringBuilder buffer = new StringBuilder(64);
            format(buffer,":INFO:",msg,thrown);
            (==null?.:).println(buffer);
        }
    }
    public boolean isDebugEnabled()
    {
        return ( <= );
    }

    
Legacy interface where a programmatic configuration of the logger level is done as a wholesale approach.
    public void setDebugEnabled(boolean enabled)
    {
        if (enabled)
        {
            this. = ;
            for (Logger log : Log.getLoggers().values())
            {                
                if (log.getName().startsWith(getName()) && log instanceof StdErrLog)
                    ((StdErrLog)log).setLevel();
            }
        }
        else
        {
            this. = this.;
            
            for (Logger log : Log.getLoggers().values())
            {
                if (log.getName().startsWith(getName()) && log instanceof StdErrLog)
                    ((StdErrLog)log).setLevel(((StdErrLog)log).);
            }
        }
    }
    public int getLevel()
    {
        return ;
    }

    
Set the level for this logger.

Available values (LEVEL_ALL, LEVEL_DEBUG, LEVEL_INFO, LEVEL_WARN)

Parameters:
level the level to set the logger to
    public void setLevel(int level)
    {
        this. = level;
    }
    public void setStdErrStream(PrintStream stream)
    {
        this. = stream==.?null:stream;
    }
    public void debug(String msgObject... args)
    {
        if ( <= )
        {
            StringBuilder buffer = new StringBuilder(64);
            format(buffer,":DBUG:",msg,args);
            (==null?.:).println(buffer);
        }
    }
    public void debug(Throwable thrown)
    {
        debug("",thrown);
    }
    public void debug(String msgThrowable thrown)
    {
        if ( <= )
        {
            StringBuilder buffer = new StringBuilder(64);
            format(buffer,":DBUG:",msg,thrown);
            (==null?.:).println(buffer);
        }
    }
    private void format(StringBuilder bufferString levelString msgObject... args)
    {
        String d = .now();
        int ms = .lastMs();
        tag(buffer,d,ms,level);
        format(buffer,msg,args);
    }
    private void format(StringBuilder bufferString levelString msgThrowable thrown)
    {
        format(buffer,level,msg);
        if (isHideStacks())
        {
            format(buffer,String.valueOf(thrown));
        }
        else
        {
            format(buffer,thrown);
        }
    }
    private void tag(StringBuilder bufferString dint msString tag)
    {
        buffer.setLength(0);
        buffer.append(d);
        if (ms > 99)
        {
            buffer.append('.');
        }
        else if (ms > 9)
        {
            buffer.append(".0");
        }
        else
        {
            buffer.append(".00");
        }
        buffer.append(ms).append(tag);
        if ()
        {
            buffer.append();
        }
        else
        {
            buffer.append();
        }
        buffer.append(':');
        if ()
        {
            Throwable source = new Throwable();
            StackTraceElement[] frames = source.getStackTrace();
            for (int i = 0; i < frames.lengthi++)
            {
                final StackTraceElement frame = frames[i];
                String clazz = frame.getClassName();
                if (clazz.equals(StdErrLog.class.getName()) || clazz.equals(Log.class.getName()))
                {
                    continue;
                }
                if (! && clazz.startsWith("org.eclipse.jetty."))
                {
                    buffer.append(condensePackageString(clazz));
                }
                else
                {
                    buffer.append(clazz);
                }
                buffer.append('#').append(frame.getMethodName());
                if (frame.getFileName() != null)
                {
                    buffer.append('(').append(frame.getFileName()).append(':').append(frame.getLineNumber()).append(')');
                }
                buffer.append(':');
                break;
            }
        }
    }
    private void format(StringBuilder builderString msgObject... args)
    {
        if (msg == null)
        {
            msg = "";
            for (int i = 0; i < args.lengthi++)
            {
                msg += "{} ";
            }
        }
        String braces = "{}";
        int start = 0;
        for (Object arg : args)
        {
            int bracesIndex = msg.indexOf(braces,start);
            if (bracesIndex < 0)
            {
                escape(builder,msg.substring(start));
                builder.append(" ");
                builder.append(arg);
                start = msg.length();
            }
            else
            {
                escape(builder,msg.substring(start,bracesIndex));
                builder.append(String.valueOf(arg));
                start = bracesIndex + braces.length();
            }
        }
        escape(builder,msg.substring(start));
    }
    private void escape(StringBuilder builderString string)
    {
        for (int i = 0; i < string.length(); ++i)
        {
            char c = string.charAt(i);
            if (Character.isISOControl(c))
            {
                if (c == '\n')
                {
                    builder.append('|');
                }
                else if (c == '\r')
                {
                    builder.append('<');
                }
                else
                {
                    builder.append('?');
                }
            }
            else
            {
                builder.append(c);
            }
        }
    }
    private void format(StringBuilder bufferThrowable thrown)
    {
        if (thrown == null)
        {
            buffer.append("null");
        }
        else
        {
            buffer.append();
            format(buffer,thrown.toString());
            StackTraceElement[] elements = thrown.getStackTrace();
            for (int i = 0; elements != null && i < elements.lengthi++)
            {
                buffer.append().append("\tat ");
                format(buffer,elements[i].toString());
            }
            Throwable cause = thrown.getCause();
            if (cause != null && cause != thrown)
            {
                buffer.append().append("Caused by: ");
                format(buffer,cause);
            }
        }
    }


    
Create a Child Logger of this Logger.
    protected Logger newLogger(String fullname)
    {
        StdErrLog logger = new StdErrLog(fullname);
        // Preserve configuration for new loggers configuration
        logger.setPrintLongNames();
        // Let Level come from configured Properties instead - sel.setLevel(_level);
        logger.setSource();
        logger._stderr = this.;
        
        // Force the child to have any programmatic configuration
        if (!=)
            logger._level=;
        return logger;
    }
    @Override
    public String toString()
    {
        StringBuilder s = new StringBuilder();
        s.append("StdErrLog:");
        s.append();
        s.append(":LEVEL=");
        switch ()
        {
            case :
                s.append("ALL");
                break;
            case :
                s.append("DEBUG");
                break;
            case :
                s.append("INFO");
                break;
            case :
                s.append("WARN");
                break;
            default:
                s.append("?");
                break;
        }
        return s.toString();
    }
    public static void setProperties(Properties props)
    {
        .clear();
        .putAll(props);
    }
    public void ignore(Throwable ignored)
    {
        if ( <= )
        {
            StringBuilder buffer = new StringBuilder(64);
            format(buffer,":IGNORED:","",ignored);
            (==null?.:).println(buffer);
        }
    }
New to GrepCode? Check out our FAQ X