I am using Log4j as logging framework in a project I am working on. I have the following situation: Log4j is configured to write the logs into a log file. At some point, this log file is copied to another destination and deleted. Logging framework keeps working, but the logs are not written to the log file because it is deleted. Is there any way to tell Log4j to recreate the file and keep writing the logs into the log file.
Best regards, Rashid
I study the source of log4j and find log4j can't create new log file, it just print the error message to system.err when the log file was deleted
I think there are two workaround
Try This one. I do not have a Linux machine right now, so I'm not sure if it can resolve the performance issue.
Make sure you can declare this line in your log4j file
If you already declared it, you log file can delete or replace as you like. Then you rerun your program and new log file is created in this path.
I went through the source code of
log4j
. When a FileAppender/RollingFileAppender is initialized, aFileOutputStream
instance is created pointing to the File. A newFileDescriptor
object is created to represent this file connection. This is the reason, the other solutions like Monitoring the file through Cron and Creating the File in append method by overriding didn't work for me, because a new file descriptor is assigned to the new file. Log4j Writer still points to the old FileDescriptor.The solution was to check if the file is present and if not call the activeOptions method present in FileAppender Class.
Finally add this to the log4j.properties file:
Note: I have tested this for log4j 1.2.17
Try This Class
Also edit the log4j config file