Doing some things before log out or quit

I have an app that needs to perform some things when it quits. I have an “on should quit” and “on will quit” handlers, that essentially writes an empty text file when done, and the work fine, but… If the users bypass quitting the program (via command-Q or the menu) and just log out from the system, this function is bypassed. How can I make the program automatically do this function no matter how the program is ended (except of course a force quit)?
TIA, Chris
btw, just using OS 10.39 and xCode 1.5

What about assigning that task to the “On will close” handler?

on will close theObject
	if theObject's name is "MainWindow" then
		-- Write to the file and any additional tasks that should be done before the app quits 
                -- (this window will close before it quits, right?)
	end if
end will close

I haven’t put this through the ringer yet, but I have an app that checks the state of a button before closing the window and if the button is disabled (because a process is running) it quits that process before quitting the AS app. My AS app only has one window though, so I don’t know if that would work with more than one window? Seems like it should.

Dr. Scotty Delicious, Scientist.

Yeah seems like that works for me. Thanks!