Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for CustomLog #2086

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
36 changes: 34 additions & 2 deletions src/core/lombok/ConfigurationKeys.java
Expand Up @@ -25,7 +25,9 @@

import lombok.core.configuration.CallSuperType;
import lombok.core.configuration.ConfigurationKey;
import lombok.core.configuration.LogDeclaration;
import lombok.core.configuration.FlagUsageType;
import lombok.core.configuration.IdentifierName;
import lombok.core.configuration.NullCheckExceptionType;
import lombok.core.configuration.TypeName;

Expand Down Expand Up @@ -416,7 +418,7 @@ private ConfigurationKeys() {}
*
* If set the various log annotations (which make a log field) will use the stated identifier instead of {@code log} as a name.
*/
public static final ConfigurationKey<String> LOG_ANY_FIELD_NAME = new ConfigurationKey<String>("lombok.log.fieldName", "Use this name for the generated logger fields (default: 'log').") {};
public static final ConfigurationKey<IdentifierName> LOG_ANY_FIELD_NAME = new ConfigurationKey<IdentifierName>("lombok.log.fieldName", "Use this name for the generated logger fields (default: 'log').") {};

/**
* lombok configuration: {@code lombok.log.fieldIsStatic} = {@code true} | {@code false}.
Expand All @@ -427,6 +429,36 @@ private ConfigurationKeys() {}
*/
public static final ConfigurationKey<Boolean> LOG_ANY_FIELD_IS_STATIC = new ConfigurationKey<Boolean>("lombok.log.fieldIsStatic", "Make the generated logger fields static (default: true).") {};

// ----- Custom Logging -----

/**
* lombok configuration: {@code lombok.log.custom.flagUsage} = {@code WARNING} | {@code ERROR}.
*
* If set, <em>any</em> usage of {@code @CustomLog} results in a warning / error.
*/
public static final ConfigurationKey<FlagUsageType> LOG_CUSTOM_FLAG_USAGE = new ConfigurationKey<FlagUsageType>("lombok.log.custom.flagUsage", "Emit a warning or error if @CustomLog is used.") {};

/**
* lombok configuration: {@code lombok.log.custom.declaration} = &lt;String: logDeclaration&gt;.
*
* The log declaration must follow the pattern:
* <br>
* {@code [LoggerType ]LoggerFactoryType.loggerFactoryMethod(loggerFactoryMethodParams)[(loggerFactoryMethodParams)]}
* <br>
* It consists of:
* <ul>
* <li>Optional fully qualified logger type, e.g. {@code my.cool.Logger}, followed by space. If not specified, it defaults to the logger factory type.
* <li>Fully qualified logger factory type, e.g. {@code my.cool.LoggerFactory}, followed by dot.
* <li>Factory method, e.g. {@code createLogger}. The method must be defined on the logger factory type and must be static.
* <li>At least one definition of factory method parameters, e.g. {@code ()} or {@code (TOPIC,TYPE)}. The format is comma-separated list of parameters wrapped in parentheses.
* The allowed parameters are: {@code TYPE} | {@code NAME} | {@code TOPIC} | {@code NULL}.
* There can be at most one parameter definition with {@code TOPIC} and at most one without {@code TOPIC}.
* </ul>
*
* If not set, any usage of {@code @CustomLog} will result in an error.
*/
public static final ConfigurationKey<LogDeclaration> LOG_CUSTOM_DECLARATION = new ConfigurationKey<LogDeclaration>("lombok.log.custom.declaration", "Define the generated custom logger field.") {};

// ##### Experimental #####

/**
Expand Down Expand Up @@ -541,7 +573,7 @@ private ConfigurationKeys() {}
*
* The names of the constants generated by {@code @FieldNameConstants} will be prefixed with this value.
*/
public static final ConfigurationKey<String> FIELD_NAME_CONSTANTS_INNER_TYPE_NAME = new ConfigurationKey<String>("lombok.fieldNameConstants.innerTypeName", "The default name of the inner type generated by @FieldNameConstants. (default: 'Fields').") {};
public static final ConfigurationKey<IdentifierName> FIELD_NAME_CONSTANTS_INNER_TYPE_NAME = new ConfigurationKey<IdentifierName>("lombok.fieldNameConstants.innerTypeName", "The default name of the inner type generated by @FieldNameConstants. (default: 'Fields').") {};

/**
* lombok configuration: {@code lombok.fieldNameConstants.uppercase} = {@code true} | {@code false}.
Expand Down
70 changes: 70 additions & 0 deletions src/core/lombok/CustomLog.java
@@ -0,0 +1,70 @@
/*
* Copyright (C) 2019 The Project Lombok Authors.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package lombok;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
* Causes lombok to generate a logger field.
* <p>
* Complete documentation is found at <a href="https://projectlombok.org/features/Log">the project lombok features page for lombok log annotations</a>.
* <p>
* Example:
* <pre>
* &#64;CustomLog
* public class LogExample {
* }
* </pre>
* With configuration:
* <pre>
* lombok.log.custom.declaration=my.cool.Logger my.cool.LoggerFactory.getLogger(NAME)
* </pre>
*
* will generate:
*
* <pre>
* public class LogExample {
* private static final my.cool.Logger log = my.cool.LoggerFactory.getLogger(LogExample.class.getName());
* }
* </pre>
* <p>
* Configuration must be provided in lombok.config, otherwise any usage will lead to errors.
*
* This annotation is valid for classes and enumerations.<br>
* @see lombok.extern.java.Log &#64;Log
* @see lombok.extern.apachecommons.CommonsLog &#64;CommonsLog
* @see lombok.extern.log4j.Log4j &#64;Log4j
* @see lombok.extern.log4j.Log4j2 &#64;Log4j2
* @see lombok.extern.slf4j.Slf4j &#64;Slf4j
* @see lombok.extern.slf4j.XSlf4j &#64;XSlf4j
* @see lombok.extern.jbosslog.JBossLog &#64;JBossLog
* @see lombok.extern.flogger.Flogger &#64;Flogger
*/
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.TYPE)
public @interface CustomLog {
/** @return The category of the constructed Logger. By default, it will use the type where the annotation is placed. */
String topic() default "";
}
69 changes: 54 additions & 15 deletions src/core/lombok/core/configuration/ConfigurationDataType.java
Expand Up @@ -21,6 +21,8 @@
*/
package lombok.core.configuration;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;
Expand Down Expand Up @@ -97,23 +99,10 @@ public final class ConfigurationDataType {
return "[false | true]";
}
});
map.put(TypeName.class, new ConfigurationValueParser() {
@Override public Object parse(String value) {
return TypeName.valueOf(value);
}

@Override public String description() {
return "type-name";
}

@Override public String exampleValue() {
return "<fully.qualified.Type>";
}
});
SIMPLE_TYPES = map;
}

private static ConfigurationValueParser enumParser(Object enumType) {
private static ConfigurationValueParser enumParser(Type enumType) {
final Class<?> type = (Class<?>) enumType;
@SuppressWarnings("rawtypes") final Class rawType = type;

Expand Down Expand Up @@ -145,6 +134,38 @@ private static ConfigurationValueParser enumParser(Object enumType) {
};
}

private static ConfigurationValueParser valueTypeParser(Type argumentType) {
final Class<?> type = (Class<?>) argumentType;
final Method valueOfMethod = getMethod(type, "valueOf", String.class);
final Method descriptionMethod = getMethod(type, "description");
final Method exampleValueMethod = getMethod(type, "exampleValue");
return new ConfigurationValueParser() {
@Override public Object parse(String value) {
return invokeStaticMethod(valueOfMethod, value);
}

@Override public String description() {
return invokeStaticMethod(descriptionMethod);
}

@Override public String exampleValue() {
return invokeStaticMethod(exampleValueMethod);
}

@SuppressWarnings("unchecked")
private <R> R invokeStaticMethod(Method method, Object... arguments) {
try {
return (R) method.invoke(null, arguments);
} catch (IllegalAccessException e) {
throw new IllegalStateException("The method " + method.getName() + " ", e);
} catch (InvocationTargetException e) {
// There shouldn't be any checked Exception, only IllegalArgumentException is expected
throw (RuntimeException) e.getTargetException();
}
}
};
}

private final boolean isList;
private final ConfigurationValueParser parser;

Expand All @@ -155,7 +176,7 @@ public static ConfigurationDataType toDataType(Class<? extends ConfigurationKey<

Type type = keyClass.getGenericSuperclass();
if (!(type instanceof ParameterizedType)) {
throw new IllegalArgumentException("Missing type parameter in "+ type);
throw new IllegalArgumentException("Missing type parameter in " + type);
}

ParameterizedType parameterized = (ParameterizedType) type;
Expand All @@ -178,6 +199,10 @@ public static ConfigurationDataType toDataType(Class<? extends ConfigurationKey<
return new ConfigurationDataType(isList, enumParser(argumentType));
}

if (isConfigurationValueType(argumentType)) {
return new ConfigurationDataType(isList, valueTypeParser(argumentType));
}

throw new IllegalArgumentException("Unsupported type parameter in " + type);
}

Expand All @@ -203,4 +228,18 @@ public String toString() {
private static boolean isEnum(Type argumentType) {
return argumentType instanceof Class && ((Class<?>) argumentType).isEnum();
}

private static boolean isConfigurationValueType(Type argumentType) {
return argumentType instanceof Class && ConfigurationValueType.class.isAssignableFrom((Class<?>) argumentType);
}

private static Method getMethod(Class<?> argumentType, String name, Class<?>... parameterTypes) {
try {
return argumentType.getMethod(name, parameterTypes);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Method " + name + " with parameters " + Arrays.toString(parameterTypes) + "was not found.", e);
} catch (SecurityException e) {
throw new IllegalStateException("Cannot inspect methods of type " + argumentType, e);
}
}
}
36 changes: 36 additions & 0 deletions src/core/lombok/core/configuration/ConfigurationValueType.java
@@ -0,0 +1,36 @@
/*
* Copyright (C) 2013 The Project Lombok Authors.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package lombok.core.configuration;

/**
* If a type used in {@link ConfigurationKey} type argument implements this interface,
* it is expected to provide the following three static methods:
* <ul>
* <li><code>public static SELF valueOf(String value)</code>
* <li><code>public static String description()</code>
* <li><code>public static String exampleValue()</code>
* </ul>
* Based on these methods, an instance of {@link ConfigurationValueParser} is created
* and used by the configuration system.
*/
public interface ConfigurationValueType {
}
72 changes: 72 additions & 0 deletions src/core/lombok/core/configuration/IdentifierName.java
@@ -0,0 +1,72 @@
/*
* Copyright (C) 2013 The Project Lombok Authors.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package lombok.core.configuration;

import lombok.core.JavaIdentifiers;

public final class IdentifierName implements ConfigurationValueType {
private final String name;

private IdentifierName(String name) {
this.name = name;
}

public static IdentifierName valueOf(String name) {
if (name == null || name.trim().isEmpty()) {
return null;
}
String trimmedName = name.trim();
if (!JavaIdentifiers.isValidJavaIdentifier(trimmedName)) {
throw new IllegalArgumentException("Invalid identifier " + trimmedName);
}
return new IdentifierName(trimmedName);
}

public static String description() {
return "identifier-name";
}

public static String exampleValue() {
return "<javaIdentifier>";
}

@Override public boolean equals(Object obj) {
if (!(obj instanceof IdentifierName)) return false;
return name.equals(((IdentifierName) obj).name);
}

@Override public int hashCode() {
return name.hashCode();
}

@Override public String toString() {
return name;
}

public String getName() {
return name;
}

public char[] getCharArray() {
return name.toCharArray();
}
}