You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@karaf.apache.org by gn...@apache.org on 2014/04/10 16:15:58 UTC
[36/59] [abbrv] [KARAF-2852] Merge log/core and log/command
http://git-wip-us.apache.org/repos/asf/karaf/blob/7f1463c5/log/core/src/main/java/org/apache/karaf/log/core/internal/layout/ISO8601DateFormat.java
----------------------------------------------------------------------
diff --git a/log/core/src/main/java/org/apache/karaf/log/core/internal/layout/ISO8601DateFormat.java b/log/core/src/main/java/org/apache/karaf/log/core/internal/layout/ISO8601DateFormat.java
deleted file mode 100644
index 80155a0..0000000
--- a/log/core/src/main/java/org/apache/karaf/log/core/internal/layout/ISO8601DateFormat.java
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.karaf.log.core.internal.layout;
-
-import java.text.FieldPosition;
-import java.text.ParsePosition;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.TimeZone;
-
-/**
- * Copied from log4j
- */
-// Contributors: Arndt Schoenewald <ar...@ibm23093i821.mc.schoenewald.de>
-/**
- Formats a {@link Date} in the format "yyyy-MM-dd HH:mm:ss,SSS" for example
- "1999-11-27 15:49:37,459".
-
- <p>Refer to the <a
- href=http://www.cl.cam.ac.uk/~mgk25/iso-time.html>summary of the
- International Standard Date and Time Notation</a> for more
- information on this format.
-
- @since 0.7.5
-*/
-public class ISO8601DateFormat extends AbsoluteTimeDateFormat {
-
- public
- ISO8601DateFormat() {
- }
-
- public
- ISO8601DateFormat(TimeZone timeZone) {
- super(timeZone);
- }
-
- static private long lastTime;
- static private char[] lastTimeString = new char[20];
-
- /**
- Appends a date in the format "YYYY-mm-dd HH:mm:ss,SSS"
- to <code>sbuf</code>. For example: "1999-11-27 15:49:37,459".
-
- @param sbuf the <code>StringBuffer</code> to write to
- */
- public
- StringBuffer format(Date date, StringBuffer sbuf,
- FieldPosition fieldPosition) {
-
- long now = date.getTime();
- int millis = (int)(now % 1000);
-
- if ((now - millis) != lastTime) {
- // We reach this point at most once per second
- // across all threads instead of each time format()
- // is called. This saves considerable CPU time.
-
- calendar.setTime(date);
-
- int start = sbuf.length();
-
- int year = calendar.get(Calendar.YEAR);
- sbuf.append(year);
-
- String month;
- switch(calendar.get(Calendar.MONTH)) {
- case Calendar.JANUARY: month = "-01-"; break;
- case Calendar.FEBRUARY: month = "-02-"; break;
- case Calendar.MARCH: month = "-03-"; break;
- case Calendar.APRIL: month = "-04-"; break;
- case Calendar.MAY: month = "-05-"; break;
- case Calendar.JUNE: month = "-06-"; break;
- case Calendar.JULY: month = "-07-"; break;
- case Calendar.AUGUST: month = "-08-"; break;
- case Calendar.SEPTEMBER: month = "-09-"; break;
- case Calendar.OCTOBER: month = "-10-"; break;
- case Calendar.NOVEMBER: month = "-11-"; break;
- case Calendar.DECEMBER: month = "-12-"; break;
- default: month = "-NA-"; break;
- }
- sbuf.append(month);
-
- int day = calendar.get(Calendar.DAY_OF_MONTH);
- if(day < 10)
- sbuf.append('0');
- sbuf.append(day);
-
- sbuf.append(' ');
-
- int hour = calendar.get(Calendar.HOUR_OF_DAY);
- if(hour < 10) {
- sbuf.append('0');
- }
- sbuf.append(hour);
- sbuf.append(':');
-
- int mins = calendar.get(Calendar.MINUTE);
- if(mins < 10) {
- sbuf.append('0');
- }
- sbuf.append(mins);
- sbuf.append(':');
-
- int secs = calendar.get(Calendar.SECOND);
- if(secs < 10) {
- sbuf.append('0');
- }
- sbuf.append(secs);
-
- sbuf.append(',');
-
- // store the time string for next time to avoid recomputation
- sbuf.getChars(start, sbuf.length(), lastTimeString, 0);
- lastTime = now - millis;
- }
- else {
- sbuf.append(lastTimeString);
- }
-
-
- if (millis < 100)
- sbuf.append('0');
- if (millis < 10)
- sbuf.append('0');
-
- sbuf.append(millis);
- return sbuf;
- }
-
- /**
- This method does not do anything but return <code>null</code>.
- */
- public
- Date parse(java.lang.String s, ParsePosition pos) {
- return null;
- }
-}
-
http://git-wip-us.apache.org/repos/asf/karaf/blob/7f1463c5/log/core/src/main/java/org/apache/karaf/log/core/internal/layout/PatternConverter.java
----------------------------------------------------------------------
diff --git a/log/core/src/main/java/org/apache/karaf/log/core/internal/layout/PatternConverter.java b/log/core/src/main/java/org/apache/karaf/log/core/internal/layout/PatternConverter.java
deleted file mode 100644
index 0d91e8c..0000000
--- a/log/core/src/main/java/org/apache/karaf/log/core/internal/layout/PatternConverter.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.karaf.log.core.internal.layout;
-
-import org.ops4j.pax.logging.spi.PaxLoggingEvent;
-
-/**
- <p>PatternConverter is an abtract class that provides the
- formatting functionality that derived classes need.
-
- <p>Conversion specifiers in a conversion patterns are parsed to
- individual PatternConverters. Each of which is responsible for
- converting a logging event in a converter specific manner.
-
- @since 0.8.2
- */
-public abstract class PatternConverter {
- public PatternConverter next;
- int min = -1;
- int max = 0x7FFFFFFF;
- boolean leftAlign = false;
-
- protected
- PatternConverter() { }
-
- protected
- PatternConverter(FormattingInfo fi) {
- min = fi.min;
- max = fi.max;
- leftAlign = fi.leftAlign;
- }
-
- /**
- Derived pattern converters must override this method in order to
- convert conversion specifiers in the correct way.
- */
- abstract
- protected
- String convert(PaxLoggingEvent event);
-
- /**
- A template method for formatting in a converter specific way.
- */
- public
- void format(StringBuffer sbuf, PaxLoggingEvent e) {
- String s = convert(e);
-
- if(s == null) {
- if(0 < min)
- spacePad(sbuf, min);
- return;
- }
-
- int len = s.length();
-
- if(len > max)
- sbuf.append(s.substring(len-max));
- else if(len < min) {
- if(leftAlign) {
- sbuf.append(s);
- spacePad(sbuf, min-len);
- }
- else {
- spacePad(sbuf, min-len);
- sbuf.append(s);
- }
- }
- else
- sbuf.append(s);
- }
-
- static String[] SPACES = {" ", " ", " ", " ", //1,2,4,8 spaces
- " ", // 16 spaces
- " " }; // 32 spaces
-
- /**
- Fast space padding method.
- */
- public
- void spacePad(StringBuffer sbuf, int length) {
- while(length >= 32) {
- sbuf.append(SPACES[5]);
- length -= 32;
- }
-
- for(int i = 4; i >= 0; i--) {
- if((length & (1<<i)) != 0) {
- sbuf.append(SPACES[i]);
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/karaf/blob/7f1463c5/log/core/src/main/java/org/apache/karaf/log/core/internal/layout/PatternParser.java
----------------------------------------------------------------------
diff --git a/log/core/src/main/java/org/apache/karaf/log/core/internal/layout/PatternParser.java b/log/core/src/main/java/org/apache/karaf/log/core/internal/layout/PatternParser.java
deleted file mode 100644
index f61b278..0000000
--- a/log/core/src/main/java/org/apache/karaf/log/core/internal/layout/PatternParser.java
+++ /dev/null
@@ -1,560 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.karaf.log.core.internal.layout;
-
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.Map;
-
-import org.apache.log4j.spi.LoggingEvent;
-import org.ops4j.pax.logging.spi.PaxLocationInfo;
-import org.ops4j.pax.logging.spi.PaxLoggingEvent;
-
-/**
- * Copied from log4j
- */
-/**
- Most of the work of the {@link org.apache.log4j.PatternLayout} class
- is delegated to the PatternParser class.
-
- @since 0.8.2
-*/
-public class PatternParser {
-
- private static final String LINE_SEP = System.getProperty("line.separator");
-
- private static final char ESCAPE_CHAR = '%';
-
- private static final int LITERAL_STATE = 0;
- private static final int CONVERTER_STATE = 1;
- private static final int MINUS_STATE = 2;
- private static final int DOT_STATE = 3;
- private static final int MIN_STATE = 4;
- private static final int MAX_STATE = 5;
-
- static final int FULL_LOCATION_CONVERTER = 1000;
- static final int METHOD_LOCATION_CONVERTER = 1001;
- static final int CLASS_LOCATION_CONVERTER = 1002;
- static final int LINE_LOCATION_CONVERTER = 1003;
- static final int FILE_LOCATION_CONVERTER = 1004;
-
- static final int RELATIVE_TIME_CONVERTER = 2000;
- static final int THREAD_CONVERTER = 2001;
- static final int LEVEL_CONVERTER = 2002;
- static final int NDC_CONVERTER = 2003;
- static final int MESSAGE_CONVERTER = 2004;
-
- int state;
- protected StringBuffer currentLiteral = new StringBuffer(32);
- protected int patternLength;
- protected int i;
- PatternConverter head;
- PatternConverter tail;
- protected FormattingInfo formattingInfo = new FormattingInfo();
- protected String pattern;
-
- public
- PatternParser(String pattern) {
- this.pattern = pattern;
- patternLength = pattern.length();
- state = LITERAL_STATE;
- }
-
- private
- void addToList(PatternConverter pc) {
- if(head == null) {
- head = tail = pc;
- } else {
- tail.next = pc;
- tail = pc;
- }
- }
-
- protected
- String extractOption() {
- if((i < patternLength) && (pattern.charAt(i) == '{')) {
- int end = pattern.indexOf('}', i);
- if (end > i) {
- String r = pattern.substring(i + 1, end);
- i = end+1;
- return r;
- }
- }
- return null;
- }
-
-
- /**
- The option is expected to be in decimal and positive. In case of
- error, zero is returned. */
- protected
- int extractPrecisionOption() {
- String opt = extractOption();
- int r = 0;
- if(opt != null) {
- try {
- r = Integer.parseInt(opt);
- if(r <= 0) {
- //LogLog.error("Precision option (" + opt + ") isn't a positive integer.");
- r = 0;
- }
- }
- catch (NumberFormatException e) {
- //LogLog.error("Category option \""+opt+"\" not a decimal integer.", e);
- }
- }
- return r;
- }
-
- public
- PatternConverter parse() {
- char c;
- i = 0;
- while(i < patternLength) {
- c = pattern.charAt(i++);
- switch(state) {
- case LITERAL_STATE:
- // In literal state, the last char is always a literal.
- if(i == patternLength) {
- currentLiteral.append(c);
- continue;
- }
- if(c == ESCAPE_CHAR) {
- // peek at the next char.
- switch(pattern.charAt(i)) {
- case ESCAPE_CHAR:
- currentLiteral.append(c);
- i++; // move pointer
- break;
- case 'n':
- currentLiteral.append(LINE_SEP);
- i++; // move pointer
- break;
- default:
- if(currentLiteral.length() != 0) {
- addToList(new LiteralPatternConverter(
- currentLiteral.toString()));
- //LogLog.debug("Parsed LITERAL converter: \""
- // +currentLiteral+"\".");
- }
- currentLiteral.setLength(0);
- currentLiteral.append(c); // append %
- state = CONVERTER_STATE;
- formattingInfo.reset();
- }
- }
- else {
- currentLiteral.append(c);
- }
- break;
- case CONVERTER_STATE:
- currentLiteral.append(c);
- switch(c) {
- case '-':
- formattingInfo.leftAlign = true;
- break;
- case '.':
- state = DOT_STATE;
- break;
- default:
- if(c >= '0' && c <= '9') {
- formattingInfo.min = c - '0';
- state = MIN_STATE;
- }
- else
- finalizeConverter(c);
- } // switch
- break;
- case MIN_STATE:
- currentLiteral.append(c);
- if(c >= '0' && c <= '9')
- formattingInfo.min = formattingInfo.min*10 + (c - '0');
- else if(c == '.')
- state = DOT_STATE;
- else {
- finalizeConverter(c);
- }
- break;
- case DOT_STATE:
- currentLiteral.append(c);
- if(c >= '0' && c <= '9') {
- formattingInfo.max = c - '0';
- state = MAX_STATE;
- }
- else {
- //LogLog.error("Error occured in position "+i+".\n Was expecting digit, instead got char \""+c+"\".");
- state = LITERAL_STATE;
- }
- break;
- case MAX_STATE:
- currentLiteral.append(c);
- if(c >= '0' && c <= '9')
- formattingInfo.max = formattingInfo.max*10 + (c - '0');
- else {
- finalizeConverter(c);
- state = LITERAL_STATE;
- }
- break;
- } // switch
- } // while
- if(currentLiteral.length() != 0) {
- addToList(new LiteralPatternConverter(currentLiteral.toString()));
- //LogLog.debug("Parsed LITERAL converter: \""+currentLiteral+"\".");
- }
- return head;
- }
-
- protected
- void finalizeConverter(char c) {
- PatternConverter pc = null;
- switch(c) {
- case 'c':
- pc = new CategoryPatternConverter(formattingInfo,
- extractPrecisionOption());
- //LogLog.debug("CATEGORY converter.");
- //formattingInfo.dump();
- currentLiteral.setLength(0);
- break;
- case 'C':
- pc = new ClassNamePatternConverter(formattingInfo,
- extractPrecisionOption());
- //LogLog.debug("CLASS_NAME converter.");
- //formattingInfo.dump();
- currentLiteral.setLength(0);
- break;
- case 'd':
- String dateFormatStr = AbsoluteTimeDateFormat.ISO8601_DATE_FORMAT;
- DateFormat df;
- String dOpt = extractOption();
- if(dOpt != null)
- dateFormatStr = dOpt;
-
- if(dateFormatStr.equalsIgnoreCase(
- AbsoluteTimeDateFormat.ISO8601_DATE_FORMAT))
- df = new ISO8601DateFormat();
- else if(dateFormatStr.equalsIgnoreCase(
- AbsoluteTimeDateFormat.ABS_TIME_DATE_FORMAT))
- df = new AbsoluteTimeDateFormat();
- else if(dateFormatStr.equalsIgnoreCase(
- AbsoluteTimeDateFormat.DATE_AND_TIME_DATE_FORMAT))
- df = new DateTimeDateFormat();
- else {
- try {
- df = new SimpleDateFormat(dateFormatStr);
- }
- catch (IllegalArgumentException e) {
- //LogLog.error("Could not instantiate SimpleDateFormat with " + dateFormatStr, e);
- df = new ISO8601DateFormat();
- }
- }
- pc = new DatePatternConverter(formattingInfo, df);
- //LogLog.debug("DATE converter {"+dateFormatStr+"}.");
- //formattingInfo.dump();
- currentLiteral.setLength(0);
- break;
- case 'F':
- pc = new LocationPatternConverter(formattingInfo,
- FILE_LOCATION_CONVERTER);
- //LogLog.debug("File name converter.");
- //formattingInfo.dump();
- currentLiteral.setLength(0);
- break;
- /*case 'l':
- pc = new LocationPatternConverter(formattingInfo,
- FULL_LOCATION_CONVERTER);
- //LogLog.debug("Location converter.");
- //formattingInfo.dump();
- currentLiteral.setLength(0);
- break;*/
- case 'L':
- pc = new LocationPatternConverter(formattingInfo,
- LINE_LOCATION_CONVERTER);
- //LogLog.debug("LINE NUMBER converter.");
- //formattingInfo.dump();
- currentLiteral.setLength(0);
- break;
- case 'm':
- pc = new BasicPatternConverter(formattingInfo, MESSAGE_CONVERTER);
- //LogLog.debug("MESSAGE converter.");
- //formattingInfo.dump();
- currentLiteral.setLength(0);
- break;
- case 'M':
- pc = new LocationPatternConverter(formattingInfo,
- METHOD_LOCATION_CONVERTER);
- //LogLog.debug("METHOD converter.");
- //formattingInfo.dump();
- currentLiteral.setLength(0);
- break;
- case 'p':
- pc = new BasicPatternConverter(formattingInfo, LEVEL_CONVERTER);
- //LogLog.debug("LEVEL converter.");
- //formattingInfo.dump();
- currentLiteral.setLength(0);
- break;
- case 'r':
- pc = new BasicPatternConverter(formattingInfo,
- RELATIVE_TIME_CONVERTER);
- //LogLog.debug("RELATIVE time converter.");
- //formattingInfo.dump();
- currentLiteral.setLength(0);
- break;
- case 't':
- pc = new BasicPatternConverter(formattingInfo, THREAD_CONVERTER);
- //LogLog.debug("THREAD converter.");
- //formattingInfo.dump();
- currentLiteral.setLength(0);
- break;
- /*case 'u':
- if(i < patternLength) {
- char cNext = pattern.charAt(i);
- if(cNext >= '0' && cNext <= '9') {
- pc = new UserFieldPatternConverter(formattingInfo, cNext - '0');
- LogLog.debug("USER converter ["+cNext+"].");
- formattingInfo.dump();
- currentLiteral.setLength(0);
- i++;
- }
- else
- LogLog.error("Unexpected char" +cNext+" at position "+i);
- }
- break;*/
- /*case 'x':
- pc = new BasicPatternConverter(formattingInfo, NDC_CONVERTER);
- //LogLog.debug("NDC converter.");
- currentLiteral.setLength(0);
- break;*/
- case 'X':
- String xOpt = extractOption();
- pc = new MDCPatternConverter(formattingInfo, xOpt);
- currentLiteral.setLength(0);
- break;
- default:
- //LogLog.error("Unexpected char [" +c+"] at position "+i+" in conversion patterrn.");
- pc = new LiteralPatternConverter(currentLiteral.toString());
- currentLiteral.setLength(0);
- }
-
- addConverter(pc);
- }
-
- protected
- void addConverter(PatternConverter pc) {
- currentLiteral.setLength(0);
- // Add the pattern converter to the list.
- addToList(pc);
- // Next pattern is assumed to be a literal.
- state = LITERAL_STATE;
- // Reset formatting info
- formattingInfo.reset();
- }
-
- // ---------------------------------------------------------------------
- // PatternConverters
- // ---------------------------------------------------------------------
-
- private static class BasicPatternConverter extends PatternConverter {
- int type;
-
- BasicPatternConverter(FormattingInfo formattingInfo, int type) {
- super(formattingInfo);
- this.type = type;
- }
-
- public
- String convert(PaxLoggingEvent event) {
- switch(type) {
- case RELATIVE_TIME_CONVERTER:
- return (Long.toString(event.getTimeStamp() - LoggingEvent.getStartTime()));
- case THREAD_CONVERTER:
- return event.getThreadName();
- case LEVEL_CONVERTER:
- return event.getLevel().toString();
- // case NDC_CONVERTER:
- //return event.getNDC();
- case MESSAGE_CONVERTER: {
- return event.getRenderedMessage();
- }
- default: return null;
- }
- }
- }
-
- private static class LiteralPatternConverter extends PatternConverter {
- private String literal;
-
- LiteralPatternConverter(String value) {
- literal = value;
- }
-
- public
- final
- void format(StringBuffer sbuf, LoggingEvent event) {
- sbuf.append(literal);
- }
-
- public
- String convert(PaxLoggingEvent event) {
- return literal;
- }
- }
-
- private static class DatePatternConverter extends PatternConverter {
- private DateFormat df;
- private Date date;
-
- DatePatternConverter(FormattingInfo formattingInfo, DateFormat df) {
- super(formattingInfo);
- date = new Date();
- this.df = df;
- }
-
- public
- String convert(PaxLoggingEvent event) {
- date.setTime(event.getTimeStamp());
- String converted = null;
- try {
- converted = df.format(date);
- }
- catch (Exception ex) {
- //LogLog.error("Error occured while converting date.", ex);
- }
- return converted;
- }
- }
-
- private class LocationPatternConverter extends PatternConverter {
- int type;
-
- LocationPatternConverter(FormattingInfo formattingInfo, int type) {
- super(formattingInfo);
- this.type = type;
- }
-
- public
- String convert(PaxLoggingEvent event) {
- PaxLocationInfo locationInfo = event.getLocationInformation();
- switch(type) {
- /*case FULL_LOCATION_CONVERTER:
- return locationInfo.fullInfo;*/
- case METHOD_LOCATION_CONVERTER:
- return locationInfo.getMethodName();
- case LINE_LOCATION_CONVERTER:
- return locationInfo.getLineNumber();
- case FILE_LOCATION_CONVERTER:
- return locationInfo.getFileName();
- default: return null;
- }
- }
- }
-
- private static abstract class NamedPatternConverter extends PatternConverter {
- int precision;
-
- NamedPatternConverter(FormattingInfo formattingInfo, int precision) {
- super(formattingInfo);
- this.precision = precision;
- }
-
- abstract
- String getFullyQualifiedName(PaxLoggingEvent event);
-
- public
- String convert(PaxLoggingEvent event) {
- String n = getFullyQualifiedName(event);
- if(precision <= 0)
- return n;
- else {
- int len = n.length();
-
- // We substract 1 from 'len' when assigning to 'end' to avoid out of
- // bounds exception in return r.substring(end+1, len). This can happen if
- // precision is 1 and the category name ends with a dot.
- int end = len -1 ;
- for(int i = precision; i > 0; i--) {
- end = n.lastIndexOf('.', end-1);
- if(end == -1)
- return n;
- }
- return n.substring(end+1, len);
- }
- }
- }
-
- private class ClassNamePatternConverter extends NamedPatternConverter {
-
- ClassNamePatternConverter(FormattingInfo formattingInfo, int precision) {
- super(formattingInfo, precision);
- }
-
- String getFullyQualifiedName(PaxLoggingEvent event) {
- return event.getLocationInformation().getClassName();
- }
- }
-
- private class CategoryPatternConverter extends NamedPatternConverter {
-
- CategoryPatternConverter(FormattingInfo formattingInfo, int precision) {
- super(formattingInfo, precision);
- }
-
- String getFullyQualifiedName(PaxLoggingEvent event) {
- return event.getLoggerName();
- }
- }
-
- private class MDCPatternConverter extends PatternConverter {
- String key;
-
- MDCPatternConverter(FormattingInfo formattingInfo, String key) {
- super(formattingInfo);
- this.key = key;
- }
-
- public
- String convert(PaxLoggingEvent event) {
- if (key == null) {
- StringBuffer buf = new StringBuffer("{");
- Map properties = event.getProperties();
- if (properties.size() > 0) {
- Object[] keys = properties.keySet().toArray();
- Arrays.sort(keys);
- for (int i = 0; i < keys.length; i++) {
- buf.append('{');
- buf.append(keys[i]);
- buf.append(',');
- buf.append(properties.get(keys[i]));
- buf.append('}');
- }
- }
- buf.append('}');
- return buf.toString();
- } else {
- Object val = event.getProperties().get(key);
- if(val == null) {
- return null;
- } else {
- return val.toString();
- }
- }
- }
-
- }
-}
-
http://git-wip-us.apache.org/repos/asf/karaf/blob/7f1463c5/log/core/src/main/java/org/apache/karaf/log/core/internal/osgi/Activator.java
----------------------------------------------------------------------
diff --git a/log/core/src/main/java/org/apache/karaf/log/core/internal/osgi/Activator.java b/log/core/src/main/java/org/apache/karaf/log/core/internal/osgi/Activator.java
deleted file mode 100644
index 2e8c4d8..0000000
--- a/log/core/src/main/java/org/apache/karaf/log/core/internal/osgi/Activator.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.karaf.log.core.internal.osgi;
-
-import java.util.Hashtable;
-
-import org.apache.karaf.log.core.LogEventFormatter;
-import org.apache.karaf.log.core.LogService;
-import org.apache.karaf.log.core.internal.LogEventFormatterImpl;
-import org.apache.karaf.log.core.internal.LogMBeanImpl;
-import org.apache.karaf.log.core.internal.LogServiceImpl;
-import org.apache.karaf.log.core.internal.LruList;
-import org.apache.karaf.util.tracker.BaseActivator;
-import org.ops4j.pax.logging.spi.PaxAppender;
-import org.osgi.service.cm.ConfigurationAdmin;
-import org.osgi.service.cm.ManagedService;
-
-public class Activator extends BaseActivator implements ManagedService {
-
- @Override
- protected void doOpen() throws Exception {
- manage("org.apache.karaf.log");
- trackService(ConfigurationAdmin.class);
- }
-
- protected void doStart() throws Exception {
- ConfigurationAdmin configurationAdmin = getTrackedService(ConfigurationAdmin.class);
- if (configurationAdmin == null) {
- return;
- }
-
- int size = getInt("size", 500);
- String pattern = getString("pattern", "%d{ABSOLUTE} | %-5.5p | %-16.16t | %-32.32c{1} | %-32.32C %4L | %m%n");
- String fatalColor = getString("fatalColor", "31");
- String errorColor = getString("errorColor", "31");
- String warnColor = getString("warnColor", "35");
- String infoColor = getString("infoColor", "36");
- String debugColor = getString("debugColor", "39");
- String traceColor = getString("traceColor", "39");
-
- LruList events = new LruList(size);
- Hashtable<String, Object> props = new Hashtable<String, Object>();
- props.put("org.ops4j.pax.logging.appender.name", "VmLogAppender");
- register(PaxAppender.class, events, props);
-
- LogEventFormatterImpl formatter = new LogEventFormatterImpl();
- formatter.setPattern(pattern);
- formatter.setFatalColor(fatalColor);
- formatter.setErrorColor(errorColor);
- formatter.setWarnColor(warnColor);
- formatter.setInfoColor(infoColor);
- formatter.setDebugColor(debugColor);
- formatter.setTraceColor(traceColor);
- register(LogEventFormatter.class, formatter);
-
- LogServiceImpl logService = new LogServiceImpl(configurationAdmin, events);
- register(LogService.class, logService);
-
- LogMBeanImpl securityMBean = new LogMBeanImpl(logService);
- registerMBean(securityMBean, "type=log");
- }
-
-}
http://git-wip-us.apache.org/repos/asf/karaf/blob/7f1463c5/log/core/src/main/resources/OSGI-INF/bundle.info
----------------------------------------------------------------------
diff --git a/log/core/src/main/resources/OSGI-INF/bundle.info b/log/core/src/main/resources/OSGI-INF/bundle.info
deleted file mode 100644
index 2bd45bd..0000000
--- a/log/core/src/main/resources/OSGI-INF/bundle.info
+++ /dev/null
@@ -1,24 +0,0 @@
-h1. Synopsis
-
-${project.name}
-
-${project.description}
-
-Maven URL:
-[mvn:${project.groupId}/${project.artifactId}/${project.version}]
-
-h1. Description
-
-The log mbean management bundle exposes a Log MBean that can be used with any JMX client (for instance JConsole).
-
-The Log MBean allows quite the same actions that can be performed using log:* commands:
- * display()
- * display(logger)
- * get()
- * get(logger)
- * set(level)
- * list(level, logger)
-
-h1. See also
-
- * Monitoring and Administration using JMX - section of the Karaf User Guide
http://git-wip-us.apache.org/repos/asf/karaf/blob/7f1463c5/log/core/src/test/java/org/apache/karaf/log/core/internal/SetLogLevelTest.java
----------------------------------------------------------------------
diff --git a/log/core/src/test/java/org/apache/karaf/log/core/internal/SetLogLevelTest.java b/log/core/src/test/java/org/apache/karaf/log/core/internal/SetLogLevelTest.java
deleted file mode 100644
index 73459d3..0000000
--- a/log/core/src/test/java/org/apache/karaf/log/core/internal/SetLogLevelTest.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.karaf.log.core.internal;
-
-import java.util.Hashtable;
-
-import junit.framework.TestCase;
-
-import org.apache.karaf.log.core.LogMBean;
-import org.apache.karaf.log.core.LogService;
-import org.easymock.EasyMock;
-import org.osgi.service.cm.Configuration;
-import org.osgi.service.cm.ConfigurationAdmin;
-
-/**
- * Test cases for {@link SetLogLevel}
- */
-@SuppressWarnings("unchecked")
-public class SetLogLevelTest extends TestCase {
-
- private static final String ROOT_LOGGER = "log4j.rootLogger";
- private static final String PACKAGE_LOGGER = "log4j.logger.org.apache.karaf.test";
-
- private LogService logService;
- private LogMBean logMBean;
- @SuppressWarnings("rawtypes")
- private Hashtable properties;
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
-
- properties = new Hashtable<String, String>();
- final Configuration configuration = EasyMock.createMock(Configuration.class);
- EasyMock.expect(configuration.getProperties()).andReturn(properties);
- configuration.update(properties);
- ConfigurationAdmin configAdmin = EasyMock.createMock(ConfigurationAdmin.class);
- EasyMock.expect(configAdmin.getConfiguration(LogServiceImpl.CONFIGURATION_PID, null)).andReturn(configuration);
- logService = new LogServiceImpl(configAdmin, new LruList(100));
- logMBean = new LogMBeanImpl(logService);
- EasyMock.replay(configAdmin);
- EasyMock.replay(configuration);
- }
-
- @Override
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- public void testInvalidLogLevel() throws Exception {
- try {
- logMBean.setLevel("INVALID");
- fail("Exception expected");
- } catch(IllegalArgumentException e) {
- // Expected
- }
- }
-
- public void testSetLogLevel() throws Exception {
- logMBean.setLevel("org.apache.karaf.test", "INFO");
- assertEquals("INFO", properties.get(PACKAGE_LOGGER));
- }
-
- public void testSetRootLogLevel() throws Exception {
- logMBean.setLevel("INFO");
- assertEquals("INFO", properties.get(ROOT_LOGGER));
- }
-
- public void testSetLogLevelLowerCase() throws Exception {
- logMBean.setLevel("org.apache.karaf.test", "info");
- assertEquals("INFO", properties.get(PACKAGE_LOGGER));
- }
-
- public void testSetRootLogLevelLowerCase() throws Exception {
- logMBean.setLevel("info");
- assertEquals("INFO", properties.get(ROOT_LOGGER));
- }
-
- public void testChangeLogLevel() throws Exception {
- properties.put(PACKAGE_LOGGER, "DEBUG");
- logMBean.setLevel("org.apache.karaf.test", "INFO");
- assertEquals("INFO", properties.get(PACKAGE_LOGGER));
- }
-
- public void testChangeRootLogLevel() throws Exception {
- properties.put(ROOT_LOGGER, "DEBUG");
- logMBean.setLevel("INFO");
- assertEquals("INFO", properties.get(ROOT_LOGGER));
- }
-
- public void testChangeLogLevelWithAppender() throws Exception {
- properties.put(PACKAGE_LOGGER, "DEBUG, APPENDER1");
- logMBean.setLevel("org.apache.karaf.test", "INFO");
- assertEquals("INFO, APPENDER1", properties.get(PACKAGE_LOGGER));
- }
-
- public void testChangeRootLogLevelWithAppender() throws Exception {
- properties.put(ROOT_LOGGER, "DEBUG, APPENDER1");
- logMBean.setLevel("INFO");
- assertEquals("INFO, APPENDER1", properties.get(ROOT_LOGGER));
- }
-
- public void testUnsetLogLevel() throws Exception {
- properties.put(PACKAGE_LOGGER, "DEBUG");
- logMBean.setLevel("org.apache.karaf.test", "DEFAULT");
- assertFalse("Configuration for logger org.apache.karaf.test has been removed", properties.containsKey(PACKAGE_LOGGER));
- }
-
- public void testUnsetRootLogLevel() throws Exception {
- properties.put(ROOT_LOGGER, "INFO");
- logMBean.setLevel("org.apache.karaf.test", "DEFAULT");
- assertEquals("Configuration for root logger should not be removed", "INFO", properties.get(ROOT_LOGGER));
- }
-
-}
http://git-wip-us.apache.org/repos/asf/karaf/blob/7f1463c5/log/pom.xml
----------------------------------------------------------------------
diff --git a/log/pom.xml b/log/pom.xml
index 9106544..5dec97a 100644
--- a/log/pom.xml
+++ b/log/pom.xml
@@ -29,13 +29,94 @@
</parent>
<groupId>org.apache.karaf.log</groupId>
- <artifactId>log</artifactId>
- <packaging>pom</packaging>
- <name>Apache Karaf :: Log</name>
+ <artifactId>org.apache.karaf.log.core</artifactId>
+ <packaging>bundle</packaging>
+ <name>Apache Karaf :: Log :: Core</name>
+ <description>Core Seervices and JMX MBean to manipulate the Karaf log layer</description>
- <modules>
- <module>core</module>
- <module>command</module>
- </modules>
+ <properties>
+ <appendedResourcesDirectory>${basedir}/../../../etc/appended-resources/</appendedResourcesDirectory>
+ </properties>
-</project>
\ No newline at end of file
+ <dependencies>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.core</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.compendium</artifactId>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.ops4j.pax.logging</groupId>
+ <artifactId>pax-logging-service</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.ops4j.pax.logging</groupId>
+ <artifactId>pax-logging-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.karaf</groupId>
+ <artifactId>org.apache.karaf.util</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.karaf.shell</groupId>
+ <artifactId>org.apache.karaf.shell.core</artifactId>
+ <optional>true</optional>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <resources>
+ <resource>
+ <directory>src/main/resources</directory>
+ <includes>
+ <include>**/*</include>
+ </includes>
+ </resource>
+ <resource>
+ <directory>src/main/resources</directory>
+ <filtering>true</filtering>
+ <includes>
+ <include>**/*.info</include>
+ </includes>
+ </resource>
+ </resources>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-bundle-plugin</artifactId>
+ <configuration>
+ <instructions>
+ <Export-Package>
+ org.apache.karaf.log.core
+ </Export-Package>
+ <Import-Package>
+ *
+ </Import-Package>
+ <Private-Package>
+ org.apache.karaf.log.command,
+ org.apache.karaf.log.core.internal,
+ org.apache.karaf.log.core.internal.layout,
+ org.apache.karaf.log.core.internal.osgi,
+ org.apache.karaf.util.tracker
+ </Private-Package>
+ <Bundle-Activator>
+ org.apache.karaf.log.core.internal.osgi.Activator
+ </Bundle-Activator>
+ <Karaf-Commands>
+ org.apache.karaf.log.command*
+ </Karaf-Commands>
+ </instructions>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+
+</project>
http://git-wip-us.apache.org/repos/asf/karaf/blob/7f1463c5/log/src/main/java/org/apache/karaf/log/command/ClearLog.java
----------------------------------------------------------------------
diff --git a/log/src/main/java/org/apache/karaf/log/command/ClearLog.java b/log/src/main/java/org/apache/karaf/log/command/ClearLog.java
new file mode 100644
index 0000000..75a48d6
--- /dev/null
+++ b/log/src/main/java/org/apache/karaf/log/command/ClearLog.java
@@ -0,0 +1,41 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.karaf.log.command;
+
+import org.apache.karaf.log.core.LogService;
+import org.apache.karaf.shell.api.action.Action;
+import org.apache.karaf.shell.api.action.Command;
+import org.apache.karaf.shell.api.action.lifecycle.Reference;
+import org.apache.karaf.shell.api.action.lifecycle.Service;
+
+/**
+ * Clear the last log entries.
+ */
+@Command(scope = "log", name = "clear", description = "Clear log entries.")
+@Service
+public class ClearLog implements Action {
+
+ @Reference
+ LogService logService;
+
+ @Override
+ public Object execute() throws Exception {
+ logService.clearEvents();
+ return null;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/karaf/blob/7f1463c5/log/src/main/java/org/apache/karaf/log/command/DisplayException.java
----------------------------------------------------------------------
diff --git a/log/src/main/java/org/apache/karaf/log/command/DisplayException.java b/log/src/main/java/org/apache/karaf/log/command/DisplayException.java
new file mode 100644
index 0000000..52a2661
--- /dev/null
+++ b/log/src/main/java/org/apache/karaf/log/command/DisplayException.java
@@ -0,0 +1,49 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.karaf.log.command;
+
+import org.apache.karaf.log.core.LogService;
+import org.apache.karaf.shell.api.action.Action;
+import org.apache.karaf.shell.api.action.Argument;
+import org.apache.karaf.shell.api.action.Command;
+import org.apache.karaf.shell.api.action.lifecycle.Reference;
+import org.apache.karaf.shell.api.action.lifecycle.Service;
+import org.ops4j.pax.logging.spi.PaxLoggingEvent;
+
+@Command(scope = "log", name = "exception-display", description = "Displays the last occurred exception from the log.")
+@Service
+public class DisplayException implements Action {
+
+ @Argument(index = 0, name = "logger", description = "The name of the logger. This can be ROOT, ALL, or the name of a logger specified in the org.ops4j.pax.logger.cfg file.", required = false, multiValued = false)
+ String logger;
+
+ @Reference
+ LogService logService;
+
+ @Override
+ public Object execute() throws Exception {
+ PaxLoggingEvent throwableEvent = logService.getLastException(logger);
+ if (throwableEvent != null) {
+ for (String r : throwableEvent.getThrowableStrRep()) {
+ System.out.println(r);
+ }
+ System.out.println();
+ }
+ return null;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/karaf/blob/7f1463c5/log/src/main/java/org/apache/karaf/log/command/DisplayLog.java
----------------------------------------------------------------------
diff --git a/log/src/main/java/org/apache/karaf/log/command/DisplayLog.java b/log/src/main/java/org/apache/karaf/log/command/DisplayLog.java
new file mode 100644
index 0000000..813eea5
--- /dev/null
+++ b/log/src/main/java/org/apache/karaf/log/command/DisplayLog.java
@@ -0,0 +1,83 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.karaf.log.command;
+
+import java.io.PrintStream;
+
+import org.apache.karaf.log.core.LogEventFormatter;
+import org.apache.karaf.log.core.LogService;
+import org.apache.karaf.shell.api.action.Action;
+import org.apache.karaf.shell.api.action.Argument;
+import org.apache.karaf.shell.api.action.Command;
+import org.apache.karaf.shell.api.action.Option;
+import org.apache.karaf.shell.api.action.lifecycle.Reference;
+import org.apache.karaf.shell.api.action.lifecycle.Service;
+import org.ops4j.pax.logging.spi.PaxLoggingEvent;
+
+/**
+ * Displays the last log entries
+ */
+@Command(scope = "log", name = "display", description = "Displays log entries.")
+@Service
+public class DisplayLog implements Action {
+
+ @Option(name = "-n", aliases = {}, description="Number of entries to display", required = false, multiValued = false)
+ int entries;
+
+ @Option(name = "-p", aliases = {}, description="Pattern for formatting the output", required = false, multiValued = false)
+ String overridenPattern;
+
+ @Option(name = "--no-color", description="Disable syntax coloring of log events", required = false, multiValued = false)
+ boolean noColor;
+
+ @Argument(index = 0, name = "logger", description = "The name of the logger. This can be ROOT, ALL, or the name of a logger specified in the org.ops4j.pax.logger.cfg file.", required = false, multiValued = false)
+ String logger;
+
+ @Reference
+ LogService logService;
+
+ @Reference
+ LogEventFormatter formatter;
+
+ @Override
+ public Object execute() throws Exception {
+
+ final PrintStream out = System.out;
+
+ Iterable<PaxLoggingEvent> le = logService.getEvents(entries == 0 ? Integer.MAX_VALUE : entries);
+ for (PaxLoggingEvent event : le) {
+ printEvent(out, event);
+ }
+ out.println();
+ return null;
+ }
+
+ protected boolean checkIfFromRequestedLog(PaxLoggingEvent event) {
+ return (event.getLoggerName().lastIndexOf(logger)>=0) ? true : false;
+ }
+
+ protected void printEvent(final PrintStream out, PaxLoggingEvent event) {
+ if ((logger != null) &&
+ (event != null)&&
+ (checkIfFromRequestedLog(event))) {
+ out.append(formatter.format(event, overridenPattern, noColor));
+ }
+ else if ((event != null)&&(logger == null)){
+ out.append(formatter.format(event, overridenPattern, noColor));
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/karaf/blob/7f1463c5/log/src/main/java/org/apache/karaf/log/command/GetLogLevel.java
----------------------------------------------------------------------
diff --git a/log/src/main/java/org/apache/karaf/log/command/GetLogLevel.java b/log/src/main/java/org/apache/karaf/log/command/GetLogLevel.java
new file mode 100644
index 0000000..83e5003
--- /dev/null
+++ b/log/src/main/java/org/apache/karaf/log/command/GetLogLevel.java
@@ -0,0 +1,63 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.karaf.log.command;
+
+import java.util.Map;
+
+import org.apache.karaf.log.core.LogService;
+import org.apache.karaf.shell.api.action.Action;
+import org.apache.karaf.shell.api.action.Argument;
+import org.apache.karaf.shell.api.action.Command;
+import org.apache.karaf.shell.api.action.Option;
+import org.apache.karaf.shell.api.action.lifecycle.Reference;
+import org.apache.karaf.shell.api.action.lifecycle.Service;
+import org.apache.karaf.shell.support.table.ShellTable;
+
+/**
+ * Get the log level
+ */
+@Command(scope = "log", name = "get", description = "Shows the currently set log level.")
+@Service
+public class GetLogLevel implements Action {
+
+ @Argument(index = 0, name = "logger", description = "The name of the logger, ALL or ROOT (default)", required = false, multiValued = false)
+ String logger;
+
+ @Option(name = "--no-format", description = "Disable table rendered output", required = false, multiValued = false)
+ boolean noFormat;
+
+ @Reference
+ LogService logService;
+
+ @Override
+ public Object execute() throws Exception {
+ Map<String, String> loggers = logService.getLevel(logger);
+
+ ShellTable table = new ShellTable();
+ table.column("Logger");
+ table.column("Level");
+
+ for (String logger : loggers.keySet()) {
+ table.addRow().addContent(logger, loggers.get(logger));
+ }
+
+ table.print(System.out, !noFormat);
+
+ return null;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/karaf/blob/7f1463c5/log/src/main/java/org/apache/karaf/log/command/LogEntry.java
----------------------------------------------------------------------
diff --git a/log/src/main/java/org/apache/karaf/log/command/LogEntry.java b/log/src/main/java/org/apache/karaf/log/command/LogEntry.java
new file mode 100644
index 0000000..d7c17a9
--- /dev/null
+++ b/log/src/main/java/org/apache/karaf/log/command/LogEntry.java
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.karaf.log.command;
+
+import org.apache.karaf.shell.api.action.Action;
+import org.apache.karaf.shell.api.action.Argument;
+import org.apache.karaf.shell.api.action.Command;
+import org.apache.karaf.shell.api.action.Completion;
+import org.apache.karaf.shell.api.action.Option;
+import org.apache.karaf.shell.api.action.lifecycle.Reference;
+import org.apache.karaf.shell.api.action.lifecycle.Service;
+import org.apache.karaf.shell.support.completers.StringsCompleter;
+import org.osgi.service.log.LogService;
+
+import java.util.HashMap;
+import java.util.Map;
+
+@Command(scope = "log", name = "log", description = "Log a message.")
+@Service
+public class LogEntry implements Action {
+
+ @Argument(index = 0, name = "message", description = "The message to log", required = true, multiValued = false)
+ private String message;
+
+ @Option(name = "--level", aliases = {"-l"}, description = "The level the message will be logged at", required = false, multiValued = false)
+ @Completion(value = StringsCompleter.class, values = { "DEBUG", "INFO", "WARNING", "ERROR" })
+ private String level = "INFO";
+
+ @Reference
+ LogService logService;
+
+ private final Map<String,Integer> mappings = new HashMap<String,Integer>();
+
+ public LogEntry() {
+ mappings.put("ERROR", 1);
+ mappings.put("WARNING", 2);
+ mappings.put("INFO", 3);
+ mappings.put("DEBUG", 4);
+ }
+
+ @Override
+ public Object execute() throws Exception {
+ logService.log(toLevel(level.toUpperCase()), message);
+ return null;
+ }
+
+ private int toLevel(String logLevel) {
+ Integer level = mappings.get(logLevel);
+ if(level == null) {
+ level = 3;
+ }
+ return level;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/karaf/blob/7f1463c5/log/src/main/java/org/apache/karaf/log/command/LogTail.java
----------------------------------------------------------------------
diff --git a/log/src/main/java/org/apache/karaf/log/command/LogTail.java b/log/src/main/java/org/apache/karaf/log/command/LogTail.java
new file mode 100644
index 0000000..bf2801e
--- /dev/null
+++ b/log/src/main/java/org/apache/karaf/log/command/LogTail.java
@@ -0,0 +1,129 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.karaf.log.command;
+
+import java.io.IOException;
+import java.io.PrintStream;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.LinkedBlockingQueue;
+
+import org.apache.karaf.log.core.LogService;
+import org.apache.karaf.shell.api.action.Command;
+import org.apache.karaf.shell.api.action.lifecycle.Reference;
+import org.apache.karaf.shell.api.action.lifecycle.Service;
+import org.apache.karaf.shell.api.console.Session;
+import org.ops4j.pax.logging.spi.PaxAppender;
+import org.ops4j.pax.logging.spi.PaxLoggingEvent;
+
+@Command(scope = "log", name = "tail", description = "Continuously display log entries. Use ctrl-c to quit this command")
+@Service
+public class LogTail extends DisplayLog {
+
+ @Reference
+ Session session;
+
+ @Reference
+ LogService logService;
+
+ private ExecutorService executorService = Executors.newSingleThreadExecutor();
+
+ @Override
+ public Object execute() throws Exception {
+ PrintEventThread printThread = new PrintEventThread();
+ executorService.execute(printThread);
+ new Thread(new ReadKeyBoardThread(this, Thread.currentThread())).start();
+ while (!Thread.currentThread().isInterrupted()) {
+ try {
+ Thread.sleep(200);
+ } catch (java.lang.InterruptedException e) {
+ break;
+ }
+ }
+ printThread.abort();
+ executorService.shutdownNow();
+ return null;
+ }
+
+ class ReadKeyBoardThread implements Runnable {
+ private LogTail logTail;
+ private Thread sessionThread;
+ public ReadKeyBoardThread(LogTail logtail, Thread thread) {
+ this.logTail = logtail;
+ this.sessionThread = thread;
+ }
+ public void run() {
+ for (;;) {
+ try {
+ int c = this.logTail.session.getKeyboard().read();
+ if (c < 0) {
+ this.sessionThread.interrupt();
+ break;
+ }
+ } catch (IOException e) {
+ break;
+ }
+
+ }
+ }
+ }
+
+ class PrintEventThread implements Runnable {
+
+ PrintStream out = System.out;
+ boolean doDisplay = true;
+
+ public void run() {
+ Iterable<PaxLoggingEvent> le = logService.getEvents(entries == 0 ? Integer.MAX_VALUE : entries);
+ for (PaxLoggingEvent event : le) {
+ if (event != null) {
+ printEvent(out, event);
+ }
+ }
+ // Tail
+ final BlockingQueue<PaxLoggingEvent> queue = new LinkedBlockingQueue<PaxLoggingEvent>();
+ PaxAppender appender = new PaxAppender() {
+ public void doAppend(PaxLoggingEvent event) {
+ queue.add(event);
+ }
+ };
+ try {
+ logService.addAppender(appender);
+
+ while (doDisplay) {
+ PaxLoggingEvent event = queue.take();
+ if (event != null) {
+ printEvent(out, event);
+ }
+ }
+ } catch (InterruptedException e) {
+ // Ignore
+ } finally {
+ logService.removeAppender(appender);
+ }
+ out.println();
+
+ }
+
+ public void abort() {
+ doDisplay = false;
+ }
+
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/karaf/blob/7f1463c5/log/src/main/java/org/apache/karaf/log/command/SetLogLevel.java
----------------------------------------------------------------------
diff --git a/log/src/main/java/org/apache/karaf/log/command/SetLogLevel.java b/log/src/main/java/org/apache/karaf/log/command/SetLogLevel.java
new file mode 100644
index 0000000..b1145b4
--- /dev/null
+++ b/log/src/main/java/org/apache/karaf/log/command/SetLogLevel.java
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.karaf.log.command;
+
+
+import org.apache.karaf.log.core.LogService;
+import org.apache.karaf.shell.api.action.Action;
+import org.apache.karaf.shell.api.action.Argument;
+import org.apache.karaf.shell.api.action.Command;
+import org.apache.karaf.shell.api.action.Completion;
+import org.apache.karaf.shell.api.action.lifecycle.Reference;
+import org.apache.karaf.shell.api.action.lifecycle.Service;
+import org.apache.karaf.shell.support.completers.StringsCompleter;
+
+/**
+ * Set the log level for a given logger
+ */
+@Command(scope = "log", name = "set", description = "Sets the log level.")
+@Service
+public class SetLogLevel implements Action {
+
+ @Argument(index = 0, name = "level", description = "The log level to set (TRACE, DEBUG, INFO, WARN, ERROR) or DEFAULT to unset", required = true, multiValued = false)
+ @Completion(value = StringsCompleter.class, values = { "TRACE", "DEBUG", "INFO", "WARN", "ERROR", "DEFAULT" })
+ String level;
+
+ @Argument(index = 1, name = "logger", description = "Logger name or ROOT (default)", required = false, multiValued = false)
+ String logger;
+
+ @Reference
+ LogService logService;
+
+ @Override
+ public Object execute() throws Exception {
+ logService.setLevel(logger, level);
+ return null;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/karaf/blob/7f1463c5/log/src/main/java/org/apache/karaf/log/core/Level.java
----------------------------------------------------------------------
diff --git a/log/src/main/java/org/apache/karaf/log/core/Level.java b/log/src/main/java/org/apache/karaf/log/core/Level.java
new file mode 100644
index 0000000..a83396f
--- /dev/null
+++ b/log/src/main/java/org/apache/karaf/log/core/Level.java
@@ -0,0 +1,54 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.karaf.log.core;
+
+/**
+ * Enumeration of available log levels for the log:set command and
+ * the command completer
+ */
+public enum Level {
+
+ TRACE,
+ DEBUG,
+ INFO,
+ WARN,
+ ERROR,
+ DEFAULT;
+
+ /**
+ * Convert the list of values into a String array
+ *
+ * @return all the values as a String array
+ */
+ public static String[] strings() {
+ String[] values = new String[values().length];
+ for (int i = 0 ; i < values.length ; i++) {
+ values[i] = values()[i].name();
+ }
+ return values;
+ }
+
+ /**
+ * Check if the string value represents the default level
+ *
+ * @param level the level value
+ * @return <code>true</code> if the value represents the {@link #DEFAULT} level
+ */
+ public static boolean isDefault(String level) {
+ return valueOf(level).equals(DEFAULT);
+ }
+}
http://git-wip-us.apache.org/repos/asf/karaf/blob/7f1463c5/log/src/main/java/org/apache/karaf/log/core/LogEventFormatter.java
----------------------------------------------------------------------
diff --git a/log/src/main/java/org/apache/karaf/log/core/LogEventFormatter.java b/log/src/main/java/org/apache/karaf/log/core/LogEventFormatter.java
new file mode 100644
index 0000000..71fe275
--- /dev/null
+++ b/log/src/main/java/org/apache/karaf/log/core/LogEventFormatter.java
@@ -0,0 +1,25 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.karaf.log.core;
+
+import org.ops4j.pax.logging.spi.PaxLoggingEvent;
+
+public interface LogEventFormatter {
+
+ public abstract String format(PaxLoggingEvent event, String overridenPattern, boolean noColor);
+
+}
http://git-wip-us.apache.org/repos/asf/karaf/blob/7f1463c5/log/src/main/java/org/apache/karaf/log/core/LogMBean.java
----------------------------------------------------------------------
diff --git a/log/src/main/java/org/apache/karaf/log/core/LogMBean.java b/log/src/main/java/org/apache/karaf/log/core/LogMBean.java
new file mode 100644
index 0000000..ad5006f
--- /dev/null
+++ b/log/src/main/java/org/apache/karaf/log/core/LogMBean.java
@@ -0,0 +1,32 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.karaf.log.core;
+
+import java.util.Map;
+
+/**
+ * Log MBean.
+ */
+public interface LogMBean {
+
+ String getLevel();
+ Map<String, String> getLevel(String logger);
+
+ void setLevel(String level);
+ void setLevel(String logger, String level);
+
+}
http://git-wip-us.apache.org/repos/asf/karaf/blob/7f1463c5/log/src/main/java/org/apache/karaf/log/core/LogService.java
----------------------------------------------------------------------
diff --git a/log/src/main/java/org/apache/karaf/log/core/LogService.java b/log/src/main/java/org/apache/karaf/log/core/LogService.java
new file mode 100644
index 0000000..ae9f678
--- /dev/null
+++ b/log/src/main/java/org/apache/karaf/log/core/LogService.java
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.karaf.log.core;
+
+import org.ops4j.pax.logging.spi.PaxAppender;
+import org.ops4j.pax.logging.spi.PaxLoggingEvent;
+
+import java.util.Map;
+
+public interface LogService {
+
+ String getLevel();
+ void setLevel(String level);
+
+ Map<String, String> getLevel(String logger);
+ void setLevel(String logger, String level);
+
+ void clearEvents();
+ Iterable<PaxLoggingEvent> getEvents();
+ Iterable<PaxLoggingEvent> getEvents(int maxNum);
+ PaxLoggingEvent getLastException(String logger);
+ void addAppender(PaxAppender appender);
+ void removeAppender(PaxAppender appender);
+}
http://git-wip-us.apache.org/repos/asf/karaf/blob/7f1463c5/log/src/main/java/org/apache/karaf/log/core/internal/LogEventFormatterImpl.java
----------------------------------------------------------------------
diff --git a/log/src/main/java/org/apache/karaf/log/core/internal/LogEventFormatterImpl.java b/log/src/main/java/org/apache/karaf/log/core/internal/LogEventFormatterImpl.java
new file mode 100644
index 0000000..0ba1f3e
--- /dev/null
+++ b/log/src/main/java/org/apache/karaf/log/core/internal/LogEventFormatterImpl.java
@@ -0,0 +1,157 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.karaf.log.core.internal;
+
+import org.apache.karaf.log.core.LogEventFormatter;
+import org.apache.karaf.log.core.internal.layout.PatternConverter;
+import org.apache.karaf.log.core.internal.layout.PatternParser;
+import org.ops4j.pax.logging.spi.PaxLoggingEvent;
+
+public class LogEventFormatterImpl implements LogEventFormatter {
+
+ protected String pattern;
+ protected String fatalColor;
+ protected String errorColor;
+ protected String warnColor;
+ protected String infoColor;
+ protected String debugColor;
+ protected String traceColor;
+
+ private static final String FATAL = "fatal";
+ private static final String ERROR = "error";
+ private static final String WARN = "warn";
+ private static final String INFO = "info";
+ private static final String DEBUG = "debug";
+ private static final String TRACE = "trace";
+
+ private static final char FIRST_ESC_CHAR = 27;
+ private static final char SECOND_ESC_CHAR = '[';
+ private static final char COMMAND_CHAR = 'm';
+
+ public String getPattern() {
+ return pattern;
+ }
+
+ public void setPattern(String pattern) {
+ this.pattern = pattern;
+ }
+
+ public String getFatalColor() {
+ return fatalColor;
+ }
+
+ public void setFatalColor(String fatalColor) {
+ this.fatalColor = fatalColor;
+ }
+
+ public String getErrorColor() {
+ return errorColor;
+ }
+
+ public void setErrorColor(String errorColor) {
+ this.errorColor = errorColor;
+ }
+
+ public String getWarnColor() {
+ return warnColor;
+ }
+
+ public void setWarnColor(String warnColor) {
+ this.warnColor = warnColor;
+ }
+
+ public String getInfoColor() {
+ return infoColor;
+ }
+
+ public void setInfoColor(String infoColor) {
+ this.infoColor = infoColor;
+ }
+
+ public String getDebugColor() {
+ return debugColor;
+ }
+
+ public void setDebugColor(String debugColor) {
+ this.debugColor = debugColor;
+ }
+
+ public String getTraceColor() {
+ return traceColor;
+ }
+
+ public void setTraceColor(String traceColor) {
+ this.traceColor = traceColor;
+ }
+
+ /* (non-Javadoc)
+ * @see org.apache.karaf.log.core.internal.LogEventFormatter#format(org.ops4j.pax.logging.spi.PaxLoggingEvent, java.lang.String, boolean)
+ */
+ @Override
+ public String format(PaxLoggingEvent event, String overridenPattern, boolean noColor) {
+ final PatternConverter cnv = new PatternParser(overridenPattern != null ? overridenPattern : pattern).parse();
+ String color = getColor(event, noColor);
+ StringBuffer sb = new StringBuffer();
+ sb.setLength(0);
+ if (color != null) {
+ sb.append(FIRST_ESC_CHAR);
+ sb.append(SECOND_ESC_CHAR);
+ sb.append(color);
+ sb.append(COMMAND_CHAR);
+ }
+ for (PatternConverter pc = cnv; pc != null; pc = pc.next) {
+ pc.format(sb, event);
+ }
+ if (event.getThrowableStrRep() != null) {
+ for (String r : event.getThrowableStrRep()) {
+ sb.append(r).append('\n');
+ }
+ }
+ if (color != null) {
+ sb.append(FIRST_ESC_CHAR);
+ sb.append(SECOND_ESC_CHAR);
+ sb.append("0");
+ sb.append(COMMAND_CHAR);
+ }
+ return sb.toString();
+ }
+
+ private String getColor(PaxLoggingEvent event, boolean noColor) {
+ String color = null;
+ if (!noColor && event != null && event.getLevel() != null && event.getLevel().toString() != null) {
+ String lvl = event.getLevel().toString().toLowerCase();
+ if (FATAL.equals(lvl)) {
+ color = fatalColor;
+ } else if (ERROR.equals(lvl)) {
+ color = errorColor;
+ } else if (WARN.equals(lvl)) {
+ color = warnColor;
+ } else if (INFO.equals(lvl)) {
+ color = infoColor;
+ } else if (DEBUG.equals(lvl)) {
+ color = debugColor;
+ } else if (TRACE.equals(lvl)) {
+ color = traceColor;
+ }
+ if (color != null && color.length() == 0) {
+ color = null;
+ }
+ }
+ return color;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/karaf/blob/7f1463c5/log/src/main/java/org/apache/karaf/log/core/internal/LogMBeanImpl.java
----------------------------------------------------------------------
diff --git a/log/src/main/java/org/apache/karaf/log/core/internal/LogMBeanImpl.java b/log/src/main/java/org/apache/karaf/log/core/internal/LogMBeanImpl.java
new file mode 100644
index 0000000..49ccbf6
--- /dev/null
+++ b/log/src/main/java/org/apache/karaf/log/core/internal/LogMBeanImpl.java
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.karaf.log.core.internal;
+
+import javax.management.NotCompliantMBeanException;
+import javax.management.StandardMBean;
+
+import org.apache.karaf.log.core.LogMBean;
+import org.apache.karaf.log.core.LogService;
+
+import java.util.Map;
+
+/**
+ * Implementation of the LogMBean.
+ */
+public class LogMBeanImpl extends StandardMBean implements LogMBean {
+
+ private final LogService logService;
+
+ public LogMBeanImpl(LogService logService) throws NotCompliantMBeanException {
+ super(LogMBean.class);
+ this.logService = logService;
+ }
+
+ @Override
+ public String getLevel() {
+ return logService.getLevel();
+ }
+
+ @Override
+ public Map<String, String> getLevel(String logger) {
+ return logService.getLevel(logger);
+ }
+
+ @Override
+ public void setLevel(String level) {
+ this.logService.setLevel(level);
+ }
+
+ @Override
+ public void setLevel(String logger, String level) {
+ this.logService.setLevel(logger, level);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/karaf/blob/7f1463c5/log/src/main/java/org/apache/karaf/log/core/internal/LogServiceImpl.java
----------------------------------------------------------------------
diff --git a/log/src/main/java/org/apache/karaf/log/core/internal/LogServiceImpl.java b/log/src/main/java/org/apache/karaf/log/core/internal/LogServiceImpl.java
new file mode 100644
index 0000000..4751873
--- /dev/null
+++ b/log/src/main/java/org/apache/karaf/log/core/internal/LogServiceImpl.java
@@ -0,0 +1,261 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.karaf.log.core.internal;
+
+import java.io.IOException;
+import java.util.Dictionary;
+import java.util.Enumeration;
+import java.util.Map;
+import java.util.TreeMap;
+
+import org.apache.karaf.log.core.Level;
+import org.apache.karaf.log.core.LogService;
+import org.ops4j.pax.logging.spi.PaxAppender;
+import org.ops4j.pax.logging.spi.PaxLoggingEvent;
+import org.osgi.service.cm.Configuration;
+import org.osgi.service.cm.ConfigurationAdmin;
+
+public class LogServiceImpl implements LogService {
+
+ static final String CONFIGURATION_PID = "org.ops4j.pax.logging";
+ static final String ROOT_LOGGER_PREFIX = "log4j.rootLogger";
+ static final String LOGGER_PREFIX = "log4j.logger.";
+ static final String ALL_LOGGER = "ALL";
+ static final String ROOT_LOGGER = "ROOT";
+
+ private final ConfigurationAdmin configAdmin;
+ private final LruList events;
+
+ public LogServiceImpl(ConfigurationAdmin configAdmin, LruList events) {
+ this.configAdmin = configAdmin;
+ this.events = events;
+ }
+
+ public String getLevel() {
+ return getLevel(null).get(ROOT_LOGGER);
+ }
+
+ public Map<String, String> getLevel(String logger) {
+ Configuration cfg;
+ try {
+ cfg = configAdmin.getConfiguration(CONFIGURATION_PID, null);
+ } catch (IOException e) {
+ throw new RuntimeException("Error retrieving Log information from config admin", e);
+ }
+ @SuppressWarnings("rawtypes")
+ Dictionary props = cfg.getProperties();
+
+ if (ROOT_LOGGER.equalsIgnoreCase(logger)) {
+ logger = null;
+ }
+
+ Map<String, String> loggers = new TreeMap<String, String>();
+
+ if (ALL_LOGGER.equalsIgnoreCase(logger)) {
+ String root = getLevelFromProperty((String) props.get(ROOT_LOGGER_PREFIX));
+ loggers.put("ROOT", root);
+ for (Enumeration e = props.keys(); e.hasMoreElements(); ) {
+ String prop = (String) e.nextElement();
+ if (prop.startsWith(LOGGER_PREFIX)) {
+ String val = getLevelFromProperty((String) props.get(prop));
+ loggers.put(prop.substring(LOGGER_PREFIX.length()), val);
+ }
+ }
+ return loggers;
+ }
+
+ String l = logger;
+ String val;
+ for (;;) {
+ String prop;
+ if (l == null) {
+ prop = ROOT_LOGGER_PREFIX;
+ } else {
+ prop = LOGGER_PREFIX + l;
+ }
+ val = (String) props.get(prop);
+ val = getLevelFromProperty(val);
+ if (val != null || l == null) {
+ break;
+ }
+ int idx = l.lastIndexOf('.');
+ if (idx < 0) {
+ l = null;
+ } else {
+ l = l.substring(0, idx);
+ }
+ }
+
+ if (logger == null)
+ logger = ROOT_LOGGER;
+
+ loggers.put(logger, val);
+
+ return loggers;
+ }
+
+ public void setLevel(String level) {
+ setLevel(null, level);
+ }
+
+ @SuppressWarnings("unchecked")
+ public void setLevel(String logger, String level) {
+ if (ROOT_LOGGER.equalsIgnoreCase(logger)) {
+ logger = null;
+ }
+
+ // make sure both uppercase and lowercase levels are supported
+ level = level.toUpperCase();
+
+ // check if the level is valid
+ Level.valueOf(level);
+
+ if (Level.isDefault(level) && logger == null) {
+ throw new IllegalStateException("Can not unset the ROOT logger");
+ }
+
+ Configuration cfg = getConfiguration();
+ Dictionary props = cfg.getProperties();
+
+ String val;
+ String prop;
+ if (logger == null) {
+ prop = ROOT_LOGGER_PREFIX;
+ } else {
+ prop = LOGGER_PREFIX + logger;
+ }
+
+ val = (String) props.get(prop);
+ if (Level.isDefault(level)) {
+ if (val != null) {
+ val = val.trim();
+ int idx = val.indexOf(",");
+ if (idx < 0) {
+ val = null;
+ } else {
+ val = val.substring(idx);
+ }
+ }
+ } else {
+ if (val == null) {
+ val = level;
+ } else {
+ val = val.trim();
+ int idx = val.indexOf(",");
+ if (idx < 0) {
+ val = level;
+ } else {
+ val = level + val.substring(idx);
+ }
+ }
+ }
+ if (val == null) {
+ props.remove(prop);
+ } else {
+ props.put(prop, val);
+ }
+ try {
+ cfg.update(props);
+ } catch (IOException e) {
+ throw new RuntimeException("Error writing log config to config admin", e);
+ }
+ }
+
+ private boolean checkIfFromRequestedLog(PaxLoggingEvent event, String logger) {
+ return (event.getLoggerName().lastIndexOf(logger) >= 0) ? true : false;
+ }
+
+ private String getLevelFromProperty(String prop) {
+ if (prop == null) {
+ return null;
+ } else {
+ String val = prop.trim();
+ int idx = val.indexOf(",");
+ if (idx == 0) {
+ val = null;
+ } else if (idx > 0) {
+ val = val.substring(0, idx);
+ }
+ return val;
+ }
+ }
+
+ private Configuration getConfiguration() {
+ try {
+ return configAdmin.getConfiguration(CONFIGURATION_PID, null);
+ } catch (IOException e) {
+ throw new RuntimeException("Error retrieving Log information from config admin", e);
+ }
+ }
+
+ @Override
+ public Iterable<PaxLoggingEvent> getEvents() {
+ return events.getElements();
+ }
+
+ @Override
+ public Iterable<PaxLoggingEvent> getEvents(int maxNum) {
+ return events.getElements(maxNum);
+ }
+
+ @Override
+ public void clearEvents() {
+ events.clear();
+ }
+
+ @Override
+ public PaxLoggingEvent getLastException(String logger) {
+ PaxLoggingEvent throwableEvent = null;
+ Iterable<PaxLoggingEvent> le = getEvents();
+ for (PaxLoggingEvent event : le) {
+ // if this is an exception, and the log is the same as the requested log,
+ // then save this exception and continue iterating from oldest to newest
+ if ((event.getThrowableStrRep() != null)
+ &&(logger != null)
+ &&(checkIfFromRequestedLog(event, logger))) {
+ throwableEvent = event;
+ // Do not break, as we iterate from the oldest to the newest event
+ } else if ((event.getThrowableStrRep() != null)&&(logger == null)) {
+ // now check if there has been no log passed in, and if this is an exception
+ // then save this exception and continue iterating from oldest to newest
+ throwableEvent = event;
+ }
+ }
+
+ return throwableEvent;
+ }
+
+ @Override
+ public void addAppender(PaxAppender appender) {
+ events.addAppender(appender);
+ }
+
+ @Override
+ public void removeAppender(PaxAppender appender) {
+ events.removeAppender(appender);
+ }
+
+ public Level convertToLevel(String level) {
+ level = level.toUpperCase();
+ Level res = Level.valueOf(level);
+ if (res == null) {
+ throw new IllegalArgumentException("level must be set to TRACE, DEBUG, INFO, WARN or ERROR (or DEFAULT to unset it)");
+ }
+ return res;
+ }
+
+}