Log4j 1 的工作解决方案:
注意:getAllAppenders 将只获取活动日志。不是 log4j.xml 配置文件中定义的完整文件列表。
这是我如何在所有日志文件上设置 rwxrwxrwx 权限的方法
@SuppressWarnings("unchecked")
public static <E> E safeCastNoException(Object o, Class<E> target)
{
if(target.isInstance(o)) return (E)o;
return null;
}
{
URL file;
try
{
LogManager.resetConfiguration();
file = new URL("file:" + Log4jXMLConfigFileName);
// We override DOMConfigurator to catch Appender settings
// in parseAppender and rework file rights access
new DOMConfigurator()
{
@Override
protected Appender parseAppender(Element appenderElement)
{
Appender a = super.parseAppender(appenderElement);
FileAppender fileAppender = safeCastNoException(a, FileAppender.class);
if( fileAppender != null )
{
String filePath=fileAppender.getFile();
Path pathTofile = FileSystems.getDefault().getPath(filePath);
try
{
// Create the empty file with default permissions, etc.
Files.createFile(pathTofile);
}
catch(FileAlreadyExistsException x)
{
System.err.format("file named %s already exists, no need to recreate%n", pathTofile);
}
catch(Exception x)
{
// Some other sort of failure, such as permissions.
System.err.format("createFile error: %s%n", x);
}
try
{
//using PosixFilePermission to set file permissions 777
Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
//add owners permission
perms.add(PosixFilePermission.OWNER_READ);
perms.add(PosixFilePermission.OWNER_WRITE);
//perms.add(PosixFilePermission.OWNER_EXECUTE);
//add group permissions
perms.add(PosixFilePermission.GROUP_READ);
perms.add(PosixFilePermission.GROUP_WRITE);
//perms.add(PosixFilePermission.GROUP_EXECUTE);
//add others permissions
perms.add(PosixFilePermission.OTHERS_READ);
perms.add(PosixFilePermission.OTHERS_WRITE);
//perms.add(PosixFilePermission.OTHERS_EXECUTE);
System.out.println("Trying to set 666 posix rights to log file: " + pathTofile.toAbsolutePath().toString());
Files.setPosixFilePermissions(Paths.get(pathTofile.toAbsolutePath().toString()), perms);
}
catch(Exception x)
{
// Some other sort of failure, such as permissions.
System.err.format("chmod error: %s%n", x);
}
}
return a;
}
}.
doConfigure(file, LogManager.getLoggerRepository());
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}