下面列出了怎么用org.apache.logging.log4j.core.config.plugins.PluginConfiguration的API类实例代码及写法,或者点击链接到github查看源代码。
@PluginFactory
public static CustomJsonLayout createLayout(@PluginConfiguration final Configuration config,
@PluginAttribute(value = "locationInfo", defaultBoolean = false) final boolean locationInfo,
@PluginAttribute(value = "properties", defaultBoolean = false) final boolean properties,
@PluginAttribute(value = "propertiesAsList", defaultBoolean = false) final boolean propertiesAsList,
@PluginAttribute(value = "complete", defaultBoolean = false) final boolean complete,
@PluginAttribute(value = "compact", defaultBoolean = false) final boolean compact,
@PluginAttribute(value = "eventEol", defaultBoolean = false) final boolean eventEol,
@PluginAttribute(value = "header", defaultString = DEFAULT_HEADER) final String headerPattern,
@PluginAttribute(value = "footer", defaultString = DEFAULT_FOOTER) final String footerPattern,
@PluginAttribute(value = "charset", defaultString = "UTF-8") final Charset charset,
@PluginAttribute(value = "includeStacktrace", defaultBoolean = true) final boolean includeStacktrace,
@PluginAttribute(value = "stacktraceAsString", defaultBoolean = false) final boolean stacktraceAsString,
@PluginAttribute(value = "objectMessageAsJsonObject",
defaultBoolean = false) final boolean objectMessageAsJsonObject) {
final boolean encodeThreadContextAsList = properties && propertiesAsList;
return new CustomJsonLayout(config, locationInfo, properties, encodeThreadContextAsList, complete, compact,
eventEol, headerPattern, footerPattern, charset, includeStacktrace, stacktraceAsString,
objectMessageAsJsonObject);
}
@PluginFactory
public static AbstractCsvLayout createLayout(
// @formatter:off
@PluginConfiguration final Configuration config,
@PluginAttribute(defaultString = DEFAULT_FORMAT) final String format,
@PluginAttribute final Character delimiter,
@PluginAttribute final Character escape,
@PluginAttribute final Character quote,
@PluginAttribute final QuoteMode quoteMode,
@PluginAttribute final String nullString,
@PluginAttribute final String recordSeparator,
@PluginAttribute(defaultString = DEFAULT_CHARSET) final Charset charset,
@PluginAttribute final String header,
@PluginAttribute final String footer)
// @formatter:on
{
final CSVFormat csvFormat = createFormat(format, delimiter, escape, quote, quoteMode, nullString, recordSeparator);
return new CsvParameterLayout(config, charset, csvFormat, header, footer);
}
@PluginFactory
public static CsvLogEventLayout createLayout(
// @formatter:off
@PluginConfiguration final Configuration config,
@PluginAttribute(defaultString = DEFAULT_FORMAT) final String format,
@PluginAttribute final Character delimiter,
@PluginAttribute final Character escape,
@PluginAttribute final Character quote,
@PluginAttribute final QuoteMode quoteMode,
@PluginAttribute final String nullString,
@PluginAttribute final String recordSeparator,
@PluginAttribute(defaultString = DEFAULT_CHARSET) final Charset charset,
@PluginAttribute final String header,
@PluginAttribute final String footer)
// @formatter:on
{
final CSVFormat csvFormat = createFormat(format, delimiter, escape, quote, quoteMode, nullString, recordSeparator);
return new CsvLogEventLayout(config, charset, csvFormat, header, footer);
}
/**
* Factory method to create a LoggerConfig.
*
* @param additivity true if additive, false otherwise.
* @param level The Level to be associated with the Logger.
* @param loggerName The name of the Logger.
* @param includeLocation whether location should be passed downstream
* @param refs An array of Appender names.
* @param properties Properties to pass to the Logger.
* @param config The Configuration.
* @param filter A Filter.
* @return A new LoggerConfig.
* @since 2.6
*/
@PluginFactory
public static LoggerConfig createLogger(
// @formatter:off
@PluginAttribute(defaultBoolean = true) final boolean additivity,
@PluginAttribute final Level level,
@Required(message = "Loggers cannot be configured without a name") @PluginAttribute("name") final String loggerName,
@PluginAttribute final String includeLocation,
@PluginElement final AppenderRef[] refs,
@PluginElement final Property[] properties,
@PluginConfiguration final Configuration config,
@PluginElement final Filter filter
// @formatter:on
) {
final String name = loggerName.equals(ROOT) ? Strings.EMPTY : loggerName;
return new LoggerConfig(name, Arrays.asList(refs), filter, level, additivity, properties, config,
includeLocation(includeLocation, config));
}
@PluginFactory
public static LoggerConfig createLogger(
// @formatter:off
@PluginAttribute final String additivity,
@PluginAttribute final Level level,
@PluginAttribute final String includeLocation,
@PluginElement final AppenderRef[] refs,
@PluginElement final Property[] properties,
@PluginConfiguration final Configuration config,
@PluginElement final Filter filter) {
// @formatter:on
final List<AppenderRef> appenderRefs = Arrays.asList(refs);
final Level actualLevel = level == null ? Level.ERROR : level;
final boolean additive = Booleans.parseBoolean(additivity, true);
return new LoggerConfig(LogManager.ROOT_LOGGER_NAME, appenderRefs, filter, actualLevel, additive,
properties, config, includeLocation(includeLocation, config));
}
/**
* Create a Failover Appender.
* @param name The name of the Appender (required).
* @param primary The name of the primary Appender (required).
* @param failovers The name of one or more Appenders to fail over to (at least one is required).
* @param retryIntervalSeconds The retry interval in seconds.
* @param config The current Configuration (passed by the Configuration when the appender is created).
* @param filter A Filter (optional).
* @param ignore If {@code "true"} (default) exceptions encountered when appending events are logged; otherwise
* they are propagated to the caller.
* @return The FailoverAppender that was created.
*/
@PluginFactory
public static FailoverAppender createAppender(
@PluginAttribute @Required(message = "A name for the Appender must be specified") final String name,
@PluginAttribute @Required(message = "A primary Appender must be specified") final String primary,
@PluginElement @Required(message = "At least one failover Appender must be specified") final String[] failovers,
@PluginAliases("retryInterval") // deprecated
@PluginAttribute(defaultInt = DEFAULT_INTERVAL_SECONDS) final int retryIntervalSeconds,
@PluginConfiguration final Configuration config,
@PluginElement final Filter filter,
@PluginAttribute(defaultBoolean = true) final boolean ignoreExceptions) {
int retryIntervalMillis;
if (retryIntervalSeconds >= 0) {
retryIntervalMillis = retryIntervalSeconds * Constants.MILLIS_IN_SECONDS;
} else {
LOGGER.warn("Interval {} is less than zero. Using default", retryIntervalSeconds);
retryIntervalMillis = DEFAULT_INTERVAL_SECONDS * Constants.MILLIS_IN_SECONDS;
}
return new FailoverAppender(name, filter, primary, failovers, retryIntervalMillis, config, ignoreExceptions, Property.EMPTY_ARRAY);
}
/**
* Creates a ScheduledTriggeringPolicy.
*
* @param configuration
* the Configuration.
* @param evaluateOnStartup
* check if the file should be rolled over immediately.
* @param schedule
* the cron expression.
* @return a ScheduledTriggeringPolicy.
*/
@PluginFactory
public static CronTriggeringPolicy createPolicy(@PluginConfiguration final Configuration configuration,
@PluginAttribute final String evaluateOnStartup,
@PluginAttribute final String schedule) {
CronExpression cronExpression;
final boolean checkOnStartup = Boolean.parseBoolean(evaluateOnStartup);
if (schedule == null) {
LOGGER.info("No schedule specified, defaulting to Daily");
cronExpression = getSchedule(defaultSchedule);
} else {
cronExpression = getSchedule(schedule);
if (cronExpression == null) {
LOGGER.error("Invalid expression specified. Defaulting to Daily");
cronExpression = getSchedule(defaultSchedule);
}
}
return new CronTriggeringPolicy(cronExpression, checkOnStartup, configuration);
}
/**
* Creates the ScriptFilter.
* @param script The script to run. The script must return a boolean value. Either script or scriptFile must be
* provided.
* @param onMatch The action to take if a match occurs.
* @param onMismatch The action to take if no match occurs.
* @param configuration the configuration
* @return A ScriptFilter.
*/
// TODO Consider refactoring to use AbstractFilter.AbstractFilterBuilder
@PluginFactory
public static ScriptFilter createFilter(
@PluginElement final AbstractScript script,
@PluginAttribute final Result onMatch,
@PluginAttribute final Result onMismatch,
@PluginConfiguration final Configuration configuration) {
if (script == null) {
LOGGER.error("A Script, ScriptFile or ScriptRef element must be provided for this ScriptFilter");
return null;
}
if (script instanceof ScriptRef) {
if (configuration.getScriptManager().getScript(script.getName()) == null) {
logger.error("No script with name {} has been declared.", script.getName());
return null;
}
}
return new ScriptFilter(script, configuration, onMatch, onMismatch);
}
/**
* @since 3.0
*/
@PluginFactory
public static LoggerConfig createLogger(
@PluginAttribute final String additivity,
@PluginAttribute final Level level,
@PluginAttribute final String includeLocation,
@PluginElement final AppenderRef[] refs,
@PluginElement final Property[] properties,
@PluginConfiguration final Configuration config,
@PluginElement final Filter filter) {
final List<AppenderRef> appenderRefs = Arrays.asList(refs);
final Level actualLevel = level == null ? Level.ERROR : level;
final boolean additive = Booleans.parseBoolean(additivity, true);
return new AsyncLoggerConfig(LogManager.ROOT_LOGGER_NAME, appenderRefs, filter, actualLevel, additive,
properties, config, AsyncLoggerConfig.includeLocation(includeLocation));
}
@PluginFactory
public static AdvancedKafkaAppender createAppender(
@PluginElement("Layout") final Layout<? extends Serializable> layout,
@PluginElement("Filter") final Filter filter, //
@PluginConfiguration final Configuration configuration,
@Required(message = "No name provided for KafkaAppender") @PluginAttribute("name") final String name,
@Required(message = "No topic provided for KafkaAppender") @PluginAttribute("topic") final String topic,
@Required(
message = "No bootstrapServers provided for KafkaAppender") @PluginAttribute("bootstrapServers") final String bootstrapServers) {
final AdvancedKafkaManager advancedKafkaManager =
new AdvancedKafkaManager(configuration.getLoggerContext(), name, bootstrapServers);
return new AdvancedKafkaAppender(name, layout, filter, false, advancedKafkaManager, topic);
}
@PluginFactory
public static GelfDynamicMdcLogFields createField(@PluginConfiguration final Configuration config,
@PluginAttribute("regex") String regex) {
if (Strings.isEmpty(regex)) {
LOGGER.error("The regex is empty");
return null;
}
return new GelfDynamicMdcLogFields(regex);
}
@PluginFactory
public static GelfLogField createField(@PluginConfiguration final Configuration config,
@PluginAttribute("name") String name, @PluginAttribute("literal") String literalValue,
@PluginAttribute("mdc") String mdc, @PluginAttribute("pattern") String pattern) {
final boolean isPattern = Strings.isNotEmpty(pattern);
final boolean isLiteralValue = Strings.isNotEmpty(literalValue);
final boolean isMDC = Strings.isNotEmpty(mdc);
if (Strings.isEmpty(name)) {
LOGGER.error("The name is empty");
return null;
}
if ((isPattern && isLiteralValue) || (isPattern && isMDC) || (isLiteralValue && isMDC)) {
LOGGER.error("The pattern, literal, and mdc attributes are mutually exclusive.");
return null;
}
if (isPattern) {
PatternLayout patternLayout = newBuilder().withPattern(pattern).withConfiguration(config)
.withNoConsoleNoAnsi(false).withAlwaysWriteExceptions(false).build();
return new GelfLogField(name, null, null, patternLayout);
}
return new GelfLogField(name, literalValue, mdc, null);
}
/**
* Create the DefaultRolloverStrategy.
* @param max The maximum number of files to keep.
* @param min The minimum number of files to keep.
* @param fileIndex If set to "max" (the default), files with a higher index will be newer than files with a
* smaller index. If set to "min", file renaming and the counter will follow the Fixed Window strategy.
* @param compressionLevelStr The compression level, 0 (less) through 9 (more); applies only to ZIP files.
* @param config The Configuration.
* @return A DefaultRolloverStrategy.
*/
@PluginFactory
public static ZebraRolloverStrategy createStrategy(
@PluginAttribute("max") final String max,
@PluginAttribute("min") final String min,
@PluginAttribute("fileIndex") final String fileIndex,
@PluginAttribute("compressionLevel") final String compressionLevelStr,
@PluginConfiguration final Configuration config) {
final boolean useMax = fileIndex == null ? true : fileIndex.equalsIgnoreCase("max");
int minIndex = MIN_WINDOW_SIZE;
if (min != null) {
minIndex = Integer.parseInt(min);
if (minIndex < 1) {
LOGGER.error("Minimum window size too small. Limited to " + MIN_WINDOW_SIZE);
minIndex = MIN_WINDOW_SIZE;
}
}
int maxIndex = DEFAULT_WINDOW_SIZE;
if (max != null) {
maxIndex = Integer.parseInt(max);
if (maxIndex < minIndex) {
maxIndex = minIndex < DEFAULT_WINDOW_SIZE ? DEFAULT_WINDOW_SIZE : minIndex;
LOGGER.error("Maximum window size must be greater than the minimum windows size. Set to " + maxIndex);
}
}
final int compressionLevel = Integers.parseInt(compressionLevelStr, Deflater.DEFAULT_COMPRESSION);
return new ZebraRolloverStrategy(minIndex, maxIndex, useMax, compressionLevel, config.getStrSubstitutor());
}
@PluginFactory
public static SystemdJournalAppender createAppender(@PluginAttribute("name") final String name,
@PluginAttribute("ignoreExceptions") final String ignoreExceptionsString,
@PluginAttribute("logSource") final String logSourceString,
@PluginAttribute("logStacktrace") final String logStacktraceString,
@PluginAttribute("logLoggerName") final String logLoggerNameString,
@PluginAttribute("logAppenderName") final String logAppenderNameString,
@PluginAttribute("logThreadName") final String logThreadNameString,
@PluginAttribute("logThreadContext") final String logThreadContextString,
@PluginAttribute("threadContextPrefix") final String threadContextPrefix,
@PluginAttribute("syslogIdentifier") final String syslogIdentifier,
@PluginAttribute("syslogFacility") final String syslogFacility,
@PluginElement("Layout") final Layout<?> layout,
@PluginElement("Filter") final Filter filter,
@PluginConfiguration final Configuration config) {
final boolean ignoreExceptions = Booleans.parseBoolean(ignoreExceptionsString, true);
final boolean logSource = Booleans.parseBoolean(logSourceString, false);
final boolean logStacktrace = Booleans.parseBoolean(logStacktraceString, true);
final boolean logThreadName = Booleans.parseBoolean(logThreadNameString, true);
final boolean logLoggerName = Booleans.parseBoolean(logLoggerNameString, true);
final boolean logAppenderName = Booleans.parseBoolean(logAppenderNameString, true);
final boolean logThreadContext = Booleans.parseBoolean(logThreadContextString, true);
if (name == null) {
LOGGER.error("No name provided for SystemdJournalAppender");
return null;
}
final SystemdJournalLibrary journalLibrary;
try {
journalLibrary = Native.loadLibrary("systemd", SystemdJournalLibrary.class);
} catch (UnsatisfiedLinkError e) {
throw new RuntimeException("Failed to load systemd library." +
" Please note that JNA requires an executable temporary folder." +
" It can be explicitly defined with -Djna.tmpdir", e);
}
return new SystemdJournalAppender(name, filter, layout, ignoreExceptions, journalLibrary, logSource, logStacktrace,
logThreadName, logLoggerName, logAppenderName, logThreadContext, threadContextPrefix, syslogIdentifier, syslogFacility);
}
@PluginFactory
public static IbisXmlLayout createLayout(
@PluginConfiguration final Configuration config,
// LOG4J2-783 use platform default by default, so do not specify defaultString for charset
@PluginAttribute(value = "charset") final Charset charset,
@PluginAttribute(value = "alwaysWriteExceptions", defaultBoolean = true) final boolean alwaysWriteExceptions) {
return new IbisXmlLayout(config, charset, alwaysWriteExceptions);
}
@PluginFactory
public static IbisPatternLayout createLayout(
@PluginAttribute(value = "pattern", defaultString = IbisPatternLayout.DEFAULT_PATTERN) final String pattern,
@PluginConfiguration final Configuration config,
// LOG4J2-783 use platform default by default, so do not specify defaultString for charset
@PluginAttribute(value = "charset") final Charset charset,
@PluginAttribute(value = "alwaysWriteExceptions", defaultBoolean = true) final boolean alwaysWriteExceptions,
@PluginAttribute(value = "noConsoleNoAnsi") final boolean noConsoleNoAnsi,
@PluginAttribute(value = "disableAnsi") final boolean disableAnsi) {
return new IbisPatternLayout(config, pattern, charset, alwaysWriteExceptions, disableAnsi, noConsoleNoAnsi);
}
@PluginFactory
public static ScriptRef createReference(
// @formatter:off
@PluginAttribute("ref") final String name,
@PluginConfiguration final Configuration configuration) {
// @formatter:on
if (name == null) {
LOGGER.error("No script name provided");
return null;
}
return new ScriptRef(name, configuration.getScriptManager());
}
/**
* Creates the Properties component.
* @param properties An array of Property elements.
* @param config The Configuration.
* @return An Interpolator that includes the configuration properties.
*/
@PluginFactory
public static StrLookup configureSubstitutor(@PluginElement("Properties") final Property[] properties,
@PluginConfiguration final Configuration config) {
if (properties == null) {
return new Interpolator(config.getProperties());
}
final Map<String, String> map = new HashMap<>(config.getProperties());
for (final Property prop : properties) {
map.put(prop.getName(), prop.getValue());
}
return new Interpolator(new MapLookup(map), config.getPluginPackages());
}
/**
* Creates a PropertiesRewritePolicy.
* @param config The Configuration.
* @param props key/value pairs for the new keys and values.
* @return The PropertiesRewritePolicy.
*/
@PluginFactory
public static PropertiesRewritePolicy createPolicy(@PluginConfiguration final Configuration config,
@PluginElement("Properties") final Property[] props) {
if (props == null || props.length == 0) {
LOGGER.error("Properties must be specified for the PropertiesRewritePolicy");
return null;
}
final List<Property> properties = Arrays.asList(props);
return new PropertiesRewritePolicy(config, properties);
}
/**
* Factory method to create a LoggerConfig.
*
* @param additivity True if additive, false otherwise.
* @param level The Level to be associated with the Logger.
* @param loggerName The name of the Logger.
* @param includeLocation "true" if location should be passed downstream
* @param refs An array of Appender names.
* @param properties Properties to pass to the Logger.
* @param config The Configuration.
* @param filter A Filter.
* @return A new LoggerConfig.
* @since 3.0
*/
@PluginFactory
public static LoggerConfig createLogger(
@PluginAttribute(defaultBoolean = true) final boolean additivity,
@PluginAttribute final Level level,
@Required(message = "Loggers cannot be configured without a name") @PluginAttribute("name") final String loggerName,
@PluginAttribute final String includeLocation,
@PluginElement final AppenderRef[] refs,
@PluginElement final Property[] properties,
@PluginConfiguration final Configuration config,
@PluginElement final Filter filter) {
final String name = loggerName.equals(ROOT) ? Strings.EMPTY : loggerName;
return new AsyncLoggerConfig(name, Arrays.asList(refs), filter, level, additivity, properties, config,
includeLocation(includeLocation));
}
/**
* Create the RFC 5424 Layout.
*
* @param facility The Facility is used to try to classify the message.
* @param id The default structured data id to use when formatting according to RFC 5424.
* @param enterpriseNumber The IANA enterprise number.
* @param includeMDC Indicates whether data from the ThreadContextMap will be included in the RFC 5424 Syslog
* record. Defaults to "true:.
* @param mdcId The id to use for the MDC Structured Data Element.
* @param mdcPrefix The prefix to add to MDC key names.
* @param eventPrefix The prefix to add to event key names.
* @param newLine If true, a newline will be appended to the end of the syslog record. The default is false.
* @param escapeNL String that should be used to replace newlines within the message text.
* @param appName The value to use as the APP-NAME in the RFC 5424 syslog record.
* @param msgId The default value to be used in the MSGID field of RFC 5424 syslog records.
* @param excludes A comma separated list of MDC keys that should be excluded from the LogEvent.
* @param includes A comma separated list of MDC keys that should be included in the FlumeEvent.
* @param required A comma separated list of MDC keys that must be present in the MDC.
* @param exceptionPattern The pattern for formatting exceptions.
* @param useTlsMessageFormat If true the message will be formatted according to RFC 5425.
* @param loggerFields Container for the KeyValuePairs containing the patterns
* @param config The Configuration. Some Converters require access to the Interpolator.
* @return An Rfc5424Layout.
*/
@PluginFactory
public static Rfc5424Layout createLayout(
// @formatter:off
@PluginAttribute(defaultString = "LOCAL0") final Facility facility,
@PluginAttribute final String id,
@PluginAttribute(defaultInt = DEFAULT_ENTERPRISE_NUMBER) final int enterpriseNumber,
@PluginAttribute(defaultBoolean = true) final boolean includeMDC,
@PluginAttribute(defaultString = DEFAULT_MDCID) final String mdcId,
@PluginAttribute final String mdcPrefix,
@PluginAttribute final String eventPrefix,
@PluginAttribute final boolean newLine,
@PluginAttribute("newLineEscape") final String escapeNL,
@PluginAttribute final String appName,
@PluginAttribute("messageId") final String msgId,
@PluginAttribute("mdcExcludes") final String excludes,
@PluginAttribute("mdcIncludes") String includes,
@PluginAttribute("mdcRequired") final String required,
@PluginAttribute final String exceptionPattern,
// RFC 5425
@PluginAttribute final boolean useTlsMessageFormat,
@PluginElement final LoggerFields[] loggerFields,
@PluginConfiguration final Configuration config) {
// @formatter:on
if (includes != null && excludes != null) {
LOGGER.error("mdcIncludes and mdcExcludes are mutually exclusive. Includes wil be ignored");
includes = null;
}
return new Rfc5424Layout(config, facility, id, enterpriseNumber, includeMDC, newLine, escapeNL, mdcId,
mdcPrefix, eventPrefix, appName, msgId, excludes, includes, required, StandardCharsets.UTF_8,
exceptionPattern, useTlsMessageFormat, loggerFields);
}
@PluginFactory
public static LoghubAppender createAppender(
@PluginAttribute("name") final String name,
@PluginElement("Filter") final Filter filter,
@PluginElement("Layout") Layout<? extends Serializable> layout,
@PluginConfiguration final Configuration config,
@PluginAttribute("ignoreExceptions") final String ignore,
@PluginAttribute("project") final String project,
@PluginAttribute("logStore") final String logStore,
@PluginAttribute("endpoint") final String endpoint,
@PluginAttribute("accessKeyId") final String accessKeyId,
@PluginAttribute("accessKeySecret") final String accessKeySecret,
@PluginAttribute("stsToken") final String stsToken,
@PluginAttribute("totalSizeInBytes") final String totalSizeInBytes,
@PluginAttribute("maxBlockMs") final String maxBlockMs,
@PluginAttribute("ioThreadCount") final String ioThreadCount,
@PluginAttribute("batchSizeThresholdInBytes") final String batchSizeThresholdInBytes,
@PluginAttribute("batchCountThreshold") final String batchCountThreshold,
@PluginAttribute("lingerMs") final String lingerMs,
@PluginAttribute("retries") final String retries,
@PluginAttribute("baseRetryBackoffMs") final String baseRetryBackoffMs,
@PluginAttribute("maxRetryBackoffMs") final String maxRetryBackoffMs,
@PluginAttribute("topic") final String topic,
@PluginAttribute("source") final String source,
@PluginAttribute("timeFormat") final String timeFormat,
@PluginAttribute("timeZone") final String timeZone,
@PluginAttribute("mdcFields") final String mdcFields) {
Boolean ignoreExceptions = Booleans.parseBoolean(ignore, true);
int maxBlockMsInt = parseStrToInt(maxBlockMs, 60);
int baseRetryBackoffMsInt = parseStrToInt(baseRetryBackoffMs, 100);
int maxRetryBackoffMsInt = parseStrToInt(maxRetryBackoffMs, 100);
int lingerMsInt = parseStrToInt(lingerMs, 3000);
int batchCountThresholdInt = parseStrToInt(batchCountThreshold, 4096);
int batchSizeThresholdInBytesInt = parseStrToInt(batchSizeThresholdInBytes, 5 * 1024 * 1024);
int totalSizeInBytesInt = parseStrToInt(totalSizeInBytes, 104857600);
int retriesInt = parseStrToInt(retries, 3);
int ioThreadCountInt = parseStrToInt(ioThreadCount, 8);
String pattern = isStrEmpty(timeFormat) ? DEFAULT_TIME_FORMAT : timeFormat;
String timeZoneInfo = isStrEmpty(timeZone) ? DEFAULT_TIME_ZONE : timeZone;
DateTimeFormatter formatter = DateTimeFormat.forPattern(pattern).withZone(DateTimeZone.forID(timeZoneInfo));
return new LoghubAppender(name, filter, layout, ignoreExceptions, project, logStore, endpoint,
accessKeyId, accessKeySecret, stsToken,totalSizeInBytesInt,maxBlockMsInt,ioThreadCountInt,
batchSizeThresholdInBytesInt,batchCountThresholdInt,lingerMsInt,retriesInt,
baseRetryBackoffMsInt, maxRetryBackoffMsInt,topic, source, formatter,mdcFields);
}
@PluginFactory
public static JsonPatternLayout createLayout(@PluginAttribute(value = "charset") final Charset charset,
@PluginElement(value = "customField") CustomField[] customFieldMdcKeyNames,
@PluginConfiguration final Configuration config) {
return new JsonPatternLayout(config, charset, customFieldMdcKeyNames);
}
/**
* Create the PurgePolicy
*
* @param timeToLive the number of increments of timeUnit before the Appender should be purged.
* @param checkInterval when all appenders purged, the number of increments of timeUnit to check if any appenders appeared
* @param timeUnit the unit of time the timeToLive and the checkInterval is expressed in.
* @return The Routes container.
*/
@PluginFactory
public static PurgePolicy createPurgePolicy(
@PluginAttribute final String timeToLive,
@PluginAttribute final String checkInterval,
@PluginAttribute final String timeUnit,
@PluginConfiguration final Configuration configuration) {
if (timeToLive == null) {
LOGGER.error("A timeToLive value is required");
return null;
}
TimeUnit units;
if (timeUnit == null) {
units = TimeUnit.MINUTES;
} else {
try {
units = TimeUnit.valueOf(timeUnit.toUpperCase());
} catch (final Exception ex) {
LOGGER.error("Invalid timeUnit value {}. timeUnit set to MINUTES", timeUnit, ex);
units = TimeUnit.MINUTES;
}
}
long ttl = units.toMillis(Long.parseLong(timeToLive));
if (ttl < 0) {
LOGGER.error("timeToLive must be positive. timeToLive set to 0");
ttl = 0;
}
long ci;
if (checkInterval == null) {
ci = ttl;
} else {
ci = units.toMillis(Long.parseLong(checkInterval));
if (ci < 0) {
LOGGER.error("checkInterval must be positive. checkInterval set equal to timeToLive = {}", ttl);
ci = ttl;
}
}
return new IdlePurgePolicy(ttl, ci, configuration.getScheduler());
}
/**
* Creates the ScriptCondition.
*
* @param script The script to run. This may be a {@link Script}, a {@link ScriptFile} or a {@link ScriptRef}. The
* script must return a {@code List<PathWithAttributes>}. When the script is executed, it is provided the
* following bindings:
* <ul>
* <li>basePath - the directory from where the {@link DeleteAction Delete} action started scanning for
* files to delete. Can be used to relativize the paths in the pathList.</li>
* <li>pathList - a {@code java.util.List} containing {@link PathWithAttribute} objects. (The script is
* free to modify and return this list.)</li>
* <li>substitutor - a {@link StrSubstitutor} that can be used to look up variables embedded in the base
* dir or other properties
* <li>statusLogger - the {@link StatusLogger} that can be used to log events during script execution
* <li>any properties declared in the configuration</li>
* </ul>
* @param configuration the configuration
* @return A ScriptCondition.
*/
@PluginFactory
public static ScriptCondition createCondition(@PluginElement("Script") final AbstractScript script,
@PluginConfiguration final Configuration configuration) {
if (script == null) {
LOGGER.error("A Script, ScriptFile or ScriptRef element must be provided for this ScriptCondition");
return null;
}
if (script instanceof ScriptRef) {
if (configuration.getScriptManager().getScript(script.getName()) == null) {
LOGGER.error("ScriptCondition: No script with name {} has been declared.", script.getName());
return null;
}
}
return new ScriptCondition(script, configuration);
}
/**
* Create a DeleteAction.
*
* @param basePath base path from where to start scanning for files to delete.
* @param followLinks whether to follow symbolic links. Default is false.
* @param maxDepth The maxDepth parameter is the maximum number of levels of directories to visit. A value of 0
* means that only the starting file is visited, unless denied by the security manager. A value of
* MAX_VALUE may be used to indicate that all levels should be visited.
* @param testMode if true, files are not deleted but instead a message is printed to the <a
* href="http://logging.apache.org/log4j/2.x/manual/configuration.html#StatusMessages">status logger</a>
* at INFO level. Users can use this to do a dry run to test if their configuration works as expected.
* Default is false.
* @param PathSorter a plugin implementing the {@link PathSorter} interface
* @param PathConditions an array of path conditions (if more than one, they all need to accept a path before it is
* deleted).
* @param config The Configuration.
* @return A DeleteAction.
*/
@PluginFactory
public static DeleteAction createDeleteAction(
// @formatter:off
@PluginAttribute final String basePath,
@PluginAttribute final boolean followLinks,
@PluginAttribute(defaultInt = 1) final int maxDepth,
@PluginAttribute final boolean testMode,
@PluginElement final PathSorter sorterParameter,
@PluginElement final PathCondition[] pathConditions,
@PluginElement final ScriptCondition scriptCondition,
@PluginConfiguration final Configuration config) {
// @formatter:on
final PathSorter sorter = sorterParameter == null ? new PathSortByModificationTime(true) : sorterParameter;
return new DeleteAction(basePath, followLinks, maxDepth, testMode, sorter, pathConditions, scriptCondition,
config.getStrSubstitutor());
}
/**
* Creates a new {@link LoggerNamePatternSelector}.
*
* @param defaultPattern The default pattern to use if no logger name matches
* @param properties The pattern match rules to use
* @param alwaysWriteExceptions Write exceptions even if pattern does not
* include exception conversion
* @param disableAnsi If true, disable all ANSI escape codes
* @param noConsoleNoAnsi If true and {@link System#console()} is null,
* disable ANSI escape codes
* @param config The configuration
* @return The new pattern selector
*/
@PluginFactory
public static LoggerNamePatternSelector createSelector(
@Required(message = "Default pattern is required") @PluginAttribute(value = "defaultPattern") String defaultPattern,
@PluginElement("PatternMatch") PatternMatch[] properties,
@PluginAttribute(value = "alwaysWriteExceptions", defaultBoolean = true) boolean alwaysWriteExceptions,
@PluginAttribute("disableAnsi") boolean disableAnsi,
@PluginAttribute("noConsoleNoAnsi") boolean noConsoleNoAnsi,
@PluginConfiguration Configuration config) {
return new LoggerNamePatternSelector(defaultPattern, properties, alwaysWriteExceptions, disableAnsi, noConsoleNoAnsi, config);
}
/**
* Creates a RewriteAppender.
* @param name The name of the Appender.
* @param ignore If {@code "true"} (default) exceptions encountered when appending events are logged; otherwise
* they are propagated to the caller.
* @param appenderRefs An array of Appender names to call.
* @param config The Configuration.
* @param rewritePolicy The policy to use to modify the event.
* @param filter A Filter to filter events.
* @return The created RewriteAppender.
*/
@PluginFactory
public static RewriteAppender createAppender(
@PluginAttribute @Required(message = "No name provided for RewriteAppender") final String name,
@PluginAttribute(defaultBoolean = true) final boolean ignoreExceptions,
@PluginElement @Required(message = "No appender references defined for RewriteAppender") final AppenderRef[] appenderRefs,
@PluginConfiguration final Configuration config,
@PluginElement final RewritePolicy rewritePolicy,
@PluginElement final Filter filter) {
return new RewriteAppender(name, filter, ignoreExceptions, appenderRefs, rewritePolicy, config, Property.EMPTY_ARRAY);
}