Log: write to file

Hi,

I basically want to:

create mylog.log
log something to mylog.log

any way to get log to write to a file?

Hi,

try this


property logName : "my.log"
property logFolder : ""

set logFolder to ((path to library folder from user domain as text) & "Logs:")
write_log from "test"

on write_log from theMessage
	tell (current date) to set timestamp to short date string & space & time string & ": "
	set logFile to logFolder & logName
	try
		set the logStream to open for access file logFile with write permission
		set logFileEof to get eof of the logStream
		write timestamp & theMessage & return to logStream starting at eof as «class utf8»
		close access logStream
		return true
	on error
		try
			close access file logFile
		end try
		return false
	end try
end write_log

Thanks. Works perfectly. I’m slightly surprised it’s not simpler - AS/S would sometimes need to write error logs, e.g. if the application has little GUI or may not be visible at all.

By the way, what exactly is eof?

[E]nd [O]f [F]ile, a pointer to the last character (+1) of the file.
If EOF is set to 0, the contents of the file will be overwritten at the next write access

My fancier version, based on StefanK’s, which allows some indenting for more human readability in complex logs or troubleshooting:

property g_debug : true
property g_log_file_name : "LOG--Overnight Automation.txt"

--Log Entry Generation
--
-- with help from StephanK of MacScripter
-- http://bbs.applescript.net/viewtopic.php?pid=76607#p76607
--
on logMe(log_string, indent_level)
	if g_debug is true then --allows turning the debugger on and off so my logMe's can be left in final version
		set log_target to ("Data: Automation:Logs:" & g_log_file_name) as text
		try
			set log_file_ref to open for access file log_target with write permission
			repeat indent_level times
				write tab to log_file_ref starting at eof
			end repeat
			write ((log_string as text) & return) to log_file_ref starting at eof
			close access log_file_ref
			return true
		on error
			try
				close access file log_target
			end try
			return false
		end try
	end if
end logMe

Example uses:

my logMe("Transfer Folder Cleaner and Logger End--" & (current date), 1)
my logMe("Items over " & g_mark_days & " days: " & (number of items in files_to_mark), 2)