下面列出了怎么用org.apache.logging.log4j.core.appender.rolling.action.PathCondition的API类实例代码及写法,或者点击链接到github查看源代码。
private static DefaultRolloverStrategy createStrategyByAction(String loggerName, String loggerDir) {
IfFileName ifFileName = IfFileName.createNameCondition(null, loggerName + "\\.\\d{4}-\\d{2}-\\d{2}.*");
IfLastModified ifLastModified = IfLastModified.createAgeCondition(Duration.parse("1d"));
DeleteAction deleteAction = DeleteAction.createDeleteAction(loggerDir, false, 1, false, null,
new PathCondition[] {ifLastModified, ifFileName}, null, config);
Action[] actions = new Action[] {deleteAction};
return DefaultRolloverStrategy.createStrategy("7", "1", null, null, actions, false, config);
}
private static DeleteAction create(final String path, final boolean followLinks, final int maxDepth, final boolean testMode,
final PathCondition[] conditions) {
final Configuration config = new BasicConfigurationFactory().new BasicConfiguration();
final DeleteAction delete = DeleteAction.createDeleteAction(path, followLinks, maxDepth, testMode, null, conditions,
null, config);
return delete;
}
@Test
public void testGetFiltersReturnsConstructorValue() {
final PathCondition[] filters = {new FixedCondition(true), new FixedCondition(false)};
final DeleteAction delete = create("any", true, 0, false, filters);
assertEquals(Arrays.asList(filters), delete.getPathConditions());
}
@Test
public void testAccept() {
final PathCondition TRUE = new FixedCondition(true);
final PathCondition FALSE = new FixedCondition(false);
assertTrue(IfAll.createAndCondition(TRUE, TRUE).accept(null, null, null));
assertFalse(IfAll.createAndCondition(FALSE, TRUE).accept(null, null, null));
assertFalse(IfAll.createAndCondition(TRUE, FALSE).accept(null, null, null));
assertFalse(IfAll.createAndCondition(FALSE, FALSE).accept(null, null, null));
}
public void init() throws Exception {
String active = (String) this.systemParams.get(INIT_PROP_LOG_ACTIVE_FILE_OUTPUT);
if (StringUtils.isEmpty(active) || !active.equalsIgnoreCase("true")) {
return;
}
String appenderName = "ENTANDO";
String conversionPattern = (String) this.systemParams.get("log4jConversionPattern");
if (StringUtils.isBlank(conversionPattern)) {
conversionPattern = "%d{yyyy-MM-dd HH:mm:ss.SSS} - %-5p - %c - %m%n";
}
String maxFileSize = (String) this.systemParams.get(INIT_PROP_LOG_FILE_SIZE);
if (StringUtils.isBlank(maxFileSize)) {
maxFileSize = "1MB"; //default size
} else {
long mega = new Long(maxFileSize) / KILOBYTE;
maxFileSize = mega + "KB";
}
String filePattern = (String) this.systemParams.get(INIT_PROP_LOG_FILE_PATTERN);
String filename = (String) this.systemParams.get(INIT_PROP_LOG_NAME);
int maxBackupIndex = Integer.parseInt((String) this.systemParams.get(INIT_PROP_LOG_FILES_COUNT));
String log4jLevelString = (String) this.systemParams.get(INIT_PROP_LOG_LEVEL);
if (StringUtils.isBlank(log4jLevelString)) {
log4jLevelString = "INFO"; //default level
}
Configurator.setRootLevel(Level.getLevel(log4jLevelString));
LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false);
loggerContext.getRootLogger().setLevel(Level.getLevel(log4jLevelString));
Configurator.setAllLevels(loggerContext.getRootLogger().getName(), Level.getLevel(log4jLevelString));
Configuration configuration = loggerContext.getConfiguration();
RollingFileAppender fileAppender = (RollingFileAppender) configuration.getAppender(appenderName);
if (null == fileAppender) {
PathCondition[] pathConditions = new PathCondition[]{IfAccumulatedFileCount.createFileCountCondition(maxBackupIndex)};
String basePath = filePattern.substring(0, filePattern.lastIndexOf(File.separator));
DeleteAction deleteAction = DeleteAction.createDeleteAction(basePath, true, 1, false, null, pathConditions, null, configuration);
SizeBasedTriggeringPolicy policy = SizeBasedTriggeringPolicy.createPolicy(maxFileSize);
PatternLayout layout = PatternLayout.newBuilder().withPattern(conversionPattern).build();
DefaultRolloverStrategy strategy = DefaultRolloverStrategy.newBuilder()
.withConfig(configuration).withMax(String.valueOf(maxBackupIndex))
.withCustomActions(new Action[]{deleteAction}).build();
fileAppender = RollingFileAppender.newBuilder()
.withName(appenderName)
.setConfiguration(configuration)
.withLayout(layout)
.withFileName(filename)
.withFilePattern(filePattern)
.withPolicy(policy)
.withStrategy(strategy)
.build();
configuration.addAppender(fileAppender);
Configurator.setLevel(appenderName, Level.getLevel(log4jLevelString));
fileAppender.start();
}
AsyncAppender async = (AsyncAppender) loggerContext.getRootLogger().getAppenders().get("async");
if (null == async) {
AppenderRef ref = AppenderRef.createAppenderRef(appenderName, Level.getLevel(log4jLevelString), null);
async = AsyncAppender.newBuilder().setName("async")
.setConfiguration(configuration)
.setAppenderRefs(new AppenderRef[]{ref}).build();
configuration.addAppender(async);
loggerContext.getRootLogger().addAppender(async);
async.start();
}
loggerContext.updateLoggers();
}
/**
* Performs the rollover.
*
* @param manager The RollingFileManager name for current active log file.
* @return A RolloverDescription.
* @throws SecurityException if an error occurs.
*/
@Override
public RolloverDescription rollover(final RollingFileManager manager) throws SecurityException {
LOGGER.debug("Rolling " + currentFileName);
if (maxFiles < 0) {
return null;
}
final long startNanos = System.nanoTime();
final int fileIndex = purge(manager);
if (LOGGER.isTraceEnabled()) {
final double durationMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos);
LOGGER.trace("DirectWriteRolloverStrategy.purge() took {} milliseconds", durationMillis);
}
Action compressAction = null;
final String sourceName = getCurrentFileName(manager);
String compressedName = sourceName;
currentFileName = null;
nextIndex = fileIndex + 1;
final FileExtension fileExtension = manager.getFileExtension();
if (fileExtension != null) {
compressedName += fileExtension.getExtension();
if (tempCompressedFilePattern != null) {
final StringBuilder buf = new StringBuilder();
tempCompressedFilePattern.formatFileName(strSubstitutor, buf, fileIndex);
final String tmpCompressedName = buf.toString();
final File tmpCompressedNameFile = new File(tmpCompressedName);
final File parentFile = tmpCompressedNameFile.getParentFile();
if (parentFile != null) {
parentFile.mkdirs();
}
compressAction = new CompositeAction(
Arrays.asList(fileExtension.createCompressAction(sourceName, tmpCompressedName,
true, compressionLevel),
new FileRenameAction(tmpCompressedNameFile,
new File(compressedName), true)),
true);
} else {
compressAction = fileExtension.createCompressAction(sourceName, compressedName,
true, compressionLevel);
}
}
if (compressAction != null && manager.isAttributeViewEnabled()) {
// Propagate posix attribute view to compressed file
// @formatter:off
final Action posixAttributeViewAction = PosixViewAttributeAction.newBuilder()
.setBasePath(compressedName)
.setFollowLinks(false)
.setMaxDepth(1)
.setPathConditions(new PathCondition[0])
.setSubst(getStrSubstitutor())
.setFilePermissions(manager.getFilePermissions())
.setFileOwner(manager.getFileOwner())
.setFileGroup(manager.getFileGroup())
.build();
// @formatter:on
compressAction = new CompositeAction(Arrays.asList(compressAction, posixAttributeViewAction), false);
}
final Action asyncAction = merge(compressAction, customActions, stopCustomActionsOnError);
return new RolloverDescriptionImpl(sourceName, false, null, asyncAction);
}
/**
* Performs the rollover.
*
* @param manager The RollingFileManager name for current active log file.
* @return A RolloverDescription.
* @throws SecurityException if an error occurs.
*/
@Override
public RolloverDescription rollover(final RollingFileManager manager) throws SecurityException {
int fileIndex;
final StringBuilder buf = new StringBuilder(255);
if (minIndex == Integer.MIN_VALUE) {
final SortedMap<Integer, Path> eligibleFiles = getEligibleFiles(manager);
fileIndex = eligibleFiles.size() > 0 ? eligibleFiles.lastKey() + 1 : 1;
manager.getPatternProcessor().formatFileName(strSubstitutor, buf, fileIndex);
} else {
if (maxIndex < 0) {
return null;
}
final long startNanos = System.nanoTime();
fileIndex = purge(minIndex, maxIndex, manager);
if (fileIndex < 0) {
return null;
}
manager.getPatternProcessor().formatFileName(strSubstitutor, buf, fileIndex);
if (LOGGER.isTraceEnabled()) {
final double durationMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos);
LOGGER.trace("DefaultRolloverStrategy.purge() took {} milliseconds", durationMillis);
}
}
final String currentFileName = manager.getFileName();
String renameTo = buf.toString();
final String compressedName = renameTo;
Action compressAction = null;
final FileExtension fileExtension = manager.getFileExtension();
if (fileExtension != null) {
final File renameToFile = new File(renameTo);
renameTo = renameTo.substring(0, renameTo.length() - fileExtension.length());
if (tempCompressedFilePattern != null) {
buf.delete(0, buf.length());
tempCompressedFilePattern.formatFileName(strSubstitutor, buf, fileIndex);
final String tmpCompressedName = buf.toString();
final File tmpCompressedNameFile = new File(tmpCompressedName);
final File parentFile = tmpCompressedNameFile.getParentFile();
if (parentFile != null) {
parentFile.mkdirs();
}
compressAction = new CompositeAction(
Arrays.asList(fileExtension.createCompressAction(renameTo, tmpCompressedName,
true, compressionLevel),
new FileRenameAction(tmpCompressedNameFile,
renameToFile, true)),
true);
} else {
compressAction = fileExtension.createCompressAction(renameTo, compressedName,
true, compressionLevel);
}
}
if (currentFileName.equals(renameTo)) {
LOGGER.warn("Attempt to rename file {} to itself will be ignored", currentFileName);
return new RolloverDescriptionImpl(currentFileName, false, null, null);
}
if (compressAction != null && manager.isAttributeViewEnabled()) {
// Propagate posix attribute view to compressed file
// @formatter:off
final Action posixAttributeViewAction = PosixViewAttributeAction.newBuilder()
.setBasePath(compressedName)
.setFollowLinks(false)
.setMaxDepth(1)
.setPathConditions(new PathCondition[0])
.setSubst(getStrSubstitutor())
.setFilePermissions(manager.getFilePermissions())
.setFileOwner(manager.getFileOwner())
.setFileGroup(manager.getFileGroup())
.build();
// @formatter:on
compressAction = new CompositeAction(Arrays.asList(compressAction, posixAttributeViewAction), false);
}
final FileRenameAction renameAction = new FileRenameAction(new File(currentFileName), new File(renameTo),
manager.isRenameEmptyFiles());
final Action asyncAction = merge(compressAction, customActions, stopCustomActionsOnError);
return new RolloverDescriptionImpl(currentFileName, false, renameAction, asyncAction);
}
private static DeleteAction createAnyFilter(final String path, final boolean followLinks, final int maxDepth, final boolean testMode) {
final PathCondition[] pathFilters = {new FixedCondition(true)};
return create(path, followLinks, maxDepth, testMode, pathFilters);
}