Is it possible to retrieve a list of all appenders configured in log4j at run time?
I\'ll flesh out the scenario a little more. Given the following config how would
Working Solution for Log4j 1:
Note: getAllAppenders will get only active log. Not the full list of files defined in your log4j.xml configuration file.
Here's how I could achieve this for setting rwxrwxrwx rights on all log files
@SuppressWarnings("unchecked")
public static E safeCastNoException(Object o, Class 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 perms = new HashSet();
//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();
}
}