I am always curious how a rolling file is implemented in logs.
How would one even start creating a file writing class in any language in order to ensure that the file size is not exceeded.
The only possible solution I can think of is this:
write method:
size = file size + size of string to write
if(size > limit)
close the file writer
open file reader
read the file
close file reader
open file writer (clears the whole file)
remove the size from the beginning to accommodate for new string to write
write the new truncated string
write the string we received
This seems like a terrible implementation, but I can not think up of anything better.
Specifically I would love to see a solution in java.
EDIT: By remove size from the beginning is, let's say I have 20 byte string (which is the limit), I want to write another 3 byte string, therefore I remove 3 bytes from the beginning, and am left with end 17 bytes, and by appending the new string I have 20 bytes.
Because your question made me look into it, here's an example from the
logback
logging framework. TheRollingfileAppender#rollover()
method looks like this:As you can see, the logic is pretty similar to what you posted. They close the current
OutputStream
, perform the rollover, then open a new one (openFile()
). Obviously, this is all done in asynchronized
block since many threads are using the logger, but only one rollover should occur at a time.A
RollingPolicy
is a policy on how to perform a rollover and aTriggeringPolicy
is when to perform a rollover. Withlogback
, you usually base these policies on file size or time.