log4j 配置Java文件日志记录以在目录不存在时创建目录

pbgvytdp  于 2024-01-08  发布在  Java
关注(0)|答案(6)|浏览(198)

我正在尝试配置Java Logging API的FileHandler,以将我的服务器记录到我的主目录下的文件夹中的文件,但我不想在运行它的每台机器上都创建这些目录。
例如,在logging.properties文件中,我指定:

  1. java.util.logging.FileHandler
  2. java.util.logging.FileHandler.pattern=%h/app-logs/MyApplication/MyApplication_%u-%g.log

字符串
这将允许我在我的主目录(%h)中为MyApplication收集日志,并将旋转它们(使用%u和%g变量)。
当我在log4j.properties中指定以下内容时,Log4j支持此操作:

  1. log4j.appender.rolling.File=${user.home}/app-logs/MyApplication-log4j/MyApplication.log


它看起来像是一个针对日志文件的bug:Bug 6244047: impossible to specify driectorys to logging FileHandler unless they exist
听起来他们不打算修复它或公开任何属性来解决这个问题(除了让你的应用程序解析logging.properties或硬编码所需的路径):
它看起来像java.util.logging. FileStream不期望指定的目录可能不存在。通常,它无论如何都必须检查此条件。此外,它还必须检查目录写入权限。另一个问题是如果这些检查之一没有通过该怎么办。
一种可能性是在用户拥有适当权限的情况下在路径中创建缺少的目录。另一种可能性是抛出一个IOException,并明确指出错误所在。后一种方法看起来更一致。

mlnl4t2r

mlnl4t2r1#

log4j版本1.2.15可以做到这一点。
下面是执行此操作的代码片段

  1. public
  2. synchronized
  3. void setFile(String fileName, boolean append, boolean bufferedIO, int bufferSize)
  4. throws IOException {
  5. LogLog.debug("setFile called: "+fileName+", "+append);
  6. // It does not make sense to have immediate flush and bufferedIO.
  7. if(bufferedIO) {
  8. setImmediateFlush(false);
  9. }
  10. reset();
  11. FileOutputStream ostream = null;
  12. try {
  13. //
  14. // attempt to create file
  15. //
  16. ostream = new FileOutputStream(fileName, append);
  17. } catch(FileNotFoundException ex) {
  18. //
  19. // if parent directory does not exist then
  20. // attempt to create it and try to create file
  21. // see bug 9150
  22. //
  23. String parentName = new File(fileName).getParent();
  24. if (parentName != null) {
  25. File parentDir = new File(parentName);
  26. if(!parentDir.exists() && parentDir.mkdirs()) {
  27. ostream = new FileOutputStream(fileName, append);
  28. } else {
  29. throw ex;
  30. }
  31. } else {
  32. throw ex;
  33. }
  34. }
  35. Writer fw = createWriter(ostream);
  36. if(bufferedIO) {
  37. fw = new BufferedWriter(fw, bufferSize);
  38. }
  39. this.setQWForFiles(fw);
  40. this.fileName = fileName;
  41. this.fileAppend = append;
  42. this.bufferedIO = bufferedIO;
  43. this.bufferSize = bufferSize;
  44. writeHeader();
  45. LogLog.debug("setFile ended");
  46. }

字符串
这段代码来自于FileTender,RollingFileTender扩展了FileTender。
在这里,它不会检查我们是否有权限创建父文件夹,但如果父文件夹不存在,那么它将尝试创建父文件夹。
编辑
如果你想要一些额外的功能,你总是可以扩展RollingFileDataReader并覆盖setFile()方法。

展开查看全部
rdrgkggo

rdrgkggo2#

你可以这样写。

  1. package org.log;
  2. import java.io.IOException;
  3. import org.apache.log4j.RollingFileAppender;
  4. public class MyRollingFileAppender extends RollingFileAppender {
  5. @Override
  6. public synchronized void setFile(String fileName, boolean append,
  7. boolean bufferedIO, int bufferSize) throws IOException {
  8. //Your logic goes here
  9. super.setFile(fileName, append, bufferedIO, bufferSize);
  10. }
  11. }

字符串
那么在您的配置中,

  1. log4j.appender.fileAppender=org.log.MyRollingFileAppender


这对我来说很完美。

展开查看全部
nvbavucw

nvbavucw3#

解决Java日志框架的限制和未解决的bug:JDK-6244047 : impossible to specify directories to logging FileHandler unless they exist
我提出了两种方法(尽管只有第一种方法实际上有效),这两种方法都需要你的应用程序的static void main()方法来初始化日志系统。
例如

  1. public static void main(String[] args) {
  2. initLogging();
  3. ...
  4. }

字符串
第一种方法是硬编码您希望存在的日志目录,如果不存在则创建它们。

  1. private static void initLogging() {
  2. try {
  3. //Create logging.properties specified directory for logging in home directory
  4. //TODO: If they ever fix this bug (https://bugs.java.com/bugdatabase/view_bug?bug_id=6244047) in the Java Logging API we wouldn't need this hack
  5. File homeLoggingDir = new File (System.getProperty("user.home")+"/webwars-logs/weblings-gameplatform/");
  6. if (!homeLoggingDir.exists() ) {
  7. homeLoggingDir.mkdirs();
  8. logger.info("Creating missing logging directory: " + homeLoggingDir);
  9. }
  10. } catch(Exception e) {
  11. e.printStackTrace();
  12. }
  13. try {
  14. logger.info("[GamePlatform] : Starting...");
  15. } catch (Exception exc) {
  16. exc.printStackTrace();
  17. }
  18. }


第二种方法可以捕获IOException并创建异常中列出的目录,这种方法的问题是日志记录框架已经无法创建FileLog,因此捕获和解决错误仍然会使日志记录系统处于错误状态。

展开查看全部
ar5n3qh5

ar5n3qh54#

作为一种可能的解决方案,我认为有两种方法(看看前面的一些答案)。我可以扩展Java Logging类并编写自己的自定义处理程序。我还可以复制log4j功能并将其适应Java Logging框架。
下面是一个复制基本文件夹并创建自定义文件夹的示例,请参阅pastebin for full class
关键是openFiles()方法,它试图创建一个FileOutputStream,并检查和创建父目录,如果它不存在(我还必须复制包保护的LogManager方法,为什么他们甚至使这些包保护):

  1. // Private method to open the set of output files, based on the
  2. // configured instance variables.
  3. private void openFiles() throws IOException {
  4. LogManager manager = LogManager.getLogManager();

字符串
...

  1. // Create a lock file. This grants us exclusive access
  2. // to our set of output files, as long as we are alive.
  3. int unique = -1;
  4. for (;;) {
  5. unique++;
  6. if (unique > MAX_LOCKS) {
  7. throw new IOException("Couldn't get lock for " + pattern);
  8. }
  9. // Generate a lock file name from the "unique" int.
  10. lockFileName = generate(pattern, 0, unique).toString() + ".lck";
  11. // Now try to lock that filename.
  12. // Because some systems (e.g. Solaris) can only do file locks
  13. // between processes (and not within a process), we first check
  14. // if we ourself already have the file locked.
  15. synchronized (locks) {
  16. if (locks.get(lockFileName) != null) {
  17. // We already own this lock, for a different FileHandler
  18. // object. Try again.
  19. continue;
  20. }
  21. FileChannel fc;
  22. try {
  23. File lockFile = new File(lockFileName);
  24. if (lockFile.getParent() != null) {
  25. File lockParentDir = new File(lockFile.getParent());
  26. // create the log dir if it does not exist
  27. if (!lockParentDir.exists()) {
  28. lockParentDir.mkdirs();
  29. }
  30. }
  31. lockStream = new FileOutputStream(lockFileName);
  32. fc = lockStream.getChannel();
  33. } catch (IOException ix) {
  34. // We got an IOException while trying to open the file.
  35. // Try the next file.
  36. continue;
  37. }
  38. try {
  39. FileLock fl = fc.tryLock();
  40. if (fl == null) {
  41. // We failed to get the lock. Try next file.
  42. continue;
  43. }
  44. // We got the lock OK.
  45. } catch (IOException ix) {
  46. // We got an IOException while trying to get the lock.
  47. // This normally indicates that locking is not supported
  48. // on the target directory. We have to proceed without
  49. // getting a lock. Drop through.
  50. }
  51. // We got the lock. Remember it.
  52. locks.put(lockFileName, lockFileName);
  53. break;
  54. }
  55. }


{\fn黑体\fs22\bord1\shad0\3aHBE\4aH00\fscx67\fscy66\2cHFFFFFF\3cH808080}

展开查看全部
vom3gejh

vom3gejh5#

我通常会尽量避免静态代码,但为了绕过这个限制,这里是我刚才在我的项目中使用的方法。
我子类化了java.util.logging. FileCloud并实现了所有的构造函数及其超级调用。我在类中放置了一个静态代码块,如果我的应用程序不存在,它会在user.home文件夹中创建文件夹。
在日志属性文件中,我用新类替换了java.util.logg.FileObject。

u4vypkhs

u4vypkhs6#

错误(JDK-6244047 : impossible to specify directories to logging FileHandler unless they exist)在Java 8中已被修复。将Java版本更新到8或更高版本应无需解决此问题。

相关问题