Jano Svitok
2/20/2007 12:02:00 AM
On 2/20/07, Raymond O'connor <nappin713@yahoo.com> wrote:
> I'm trying to write a logger class. I open the file in the initialize
> method. Is there a destructor that I can override to close the file, or
> can I just assume the file is closed automatically?
>
> Am I going about this all wrong, and should instead just open and close
> the file each time I write to it?
>
> Thanks,
> Ray
1. The files are closed automatically when you stop the program.
You'll need to close in special cases, e.g. you suspect that you'll
run out of free file handles, you want to make sure that file is
properly closed asap (for the event of a powerfailure),...
2. Normally with files (and many more) you either call close() or you
can use the block form of File.open(). When the block finishes the
file gets closed. But as you need the file in the class, I think you
should provide you own close() method that will close the file, and
let the responsibility to the user of your class.
3. There are several ready-made logger packages available e.g. Logger
and Log4r. You may want to try them before reinventing the wheel ;-)
4. You may want to set File#sync=true to disable buffering on the
file. The changes will be written to the file immediately, no matter
how small. The default is to collect them and write them in larger
chunks. This helps performance-wise, but you get the info with a
little delay.