It compiles, works well, solves my problem of zipping old or big log files and removes them from a hard drive. However, following this answer, I would like to know what was wrong with the code.
Dir.foreach(FileUtils.pwd()) do |f|
if f.end_with?('log')
File.open(f) do |file|
if File.size(f) > MAX_FILE_SIZE
puts f
puts file.ctime
puts file.mtime
# zipping the file
orig = f
Zlib::GzipWriter.open('arch_log.gz') do |gz|
gz.mtime = File.mtime(orig)
gz.orig_name = orig
gz.write IO.binread(orig)
puts "File has been archived"
end
#deleting the file
begin
File.delete(f)
puts "File has been deleted"
rescue Exception => e
puts "File #{f} can not be deleted"
puts " Error #{e.message}"
puts "======= Please remove file manually =========="
end
end
end
end
end
-
1\$\begingroup\$ Ruby's indentation style is usually 2 spaces, just as a minor heads up. \$\endgroup\$Alex Nye– Alex Nye2012年11月03日 01:39:05 +00:00Commented Nov 3, 2012 at 1:39
1 Answer 1
My proposal, please see also the comments in the code.
require 'zlib'
MAX_FILE_SIZE = 1024 #One KB
#Use a glob to get all log-files
Dir["#{Dir.pwd}/*.log"].each do |f|
#skip file, if file is small
next unless File.size(f) > MAX_FILE_SIZE
#Make a one line info
puts "#{f}: #{File.size(f)/1024}KB, created #{File.ctime(f)} modified #{File.mtime(f)} "
# zipping the file - each log in a file
Zlib::GzipWriter.open("arch_#{File.basename(f)}.gz") do |gz|
gz.mtime = File.mtime(f)
gz.orig_name = File.basename(f) #filename without path
#File.read should be fine for log files. Or is there a reason for IO.binread
gz.write File.read(f)
puts "File #{f} has been archived"
end
#deleting the file
begin
#~ File.delete(f)
puts "File #{f} has been deleted"
rescue Exception => e
puts "File #{f} can not be deleted"
puts " Error #{e.message}"
puts "======= Please remove file manually =========="
end
end
Remark:
This solution creates one gz-file per log file. Your old solution created one arch_log.gz
. If there were two log-files, the 2nd would overwrite the 1st.
-
\$\begingroup\$ defintely sorry I didn't put require and global variables, thanks for a good answer \$\endgroup\$Jackie Chan– Jackie Chan2012年02月13日 11:24:50 +00:00Commented Feb 13, 2012 at 11:24
-
1\$\begingroup\$ @DanielMyasnikov if this answered the question (made a good suggestion?) then you should mark it as the selected answer. \$\endgroup\$Baylor Rae'– Baylor Rae'2012年02月14日 18:43:34 +00:00Commented Feb 14, 2012 at 18:43
-
\$\begingroup\$ @knut, no there were no reason for IO.binread, I just got if from Ruby Doc library web-site (ruby-doc.org/stdlib-1.9.3/libdoc/zlib/rdoc/Zlib/GzipWriter.html) \$\endgroup\$Jackie Chan– Jackie Chan2012年02月15日 22:48:58 +00:00Commented Feb 15, 2012 at 22:48
Explore related questions
See similar questions with these tags.