Module: OpsScript
- Defined in:
- lib/ops_script.rb,
lib/ops_script/version.rb
Overview
This module provides some basic features common to many operational unix scripts
-
Log file
-
PID file used to insure only one instance is running, handy if running from cron multiple times
-
Options processing with basic options for overriding default log attributes and logfile and pidfile location
Example
require 'ops_script'
include OpsScript
# Add your own custom options
option_parser.on "--bar", "The bar option" do
[:bar] = true
end
# Run your code
OpsScript.run do
puts "BAR" if [:bar]
log.info "My informational message"
log.debug "This is a debug message"
# do some stuff
end
The module provides these options
foo.rb -h
Usage: foo.rb [options]
--debug enable debug output
--logfile log_file specify a different log file
default is ../log/foo.log
--log-retention retention Number of old log files to keep,
or frequency of rotation (daily, weekly or monthly). Defaults to monthly.
--log-size size Max size in bytes for logfile before rotating.
Specify number of files to keep with log-retention option.
--pidfile pid_file specify a different pid file
default is ../tmp/foo.pid
-h, -?, --help Display this help
Constant Summary collapse
- VERSION =
"1.0.5"
Class Method Summary collapse
Instance Method Summary collapse
-
#log ⇒ Object
Use log in your script to log messages.
- #option_parser ⇒ Object
- #options ⇒ Object
Class Method Details
.log ⇒ Object
135 136 137 |
# File 'lib/ops_script.rb', line 135 def self.log @log ||= Logger.new([:log_file], [:log_retention] || 'monthly', [:log_size]) end |
.option_parser ⇒ Object
65 66 67 |
# File 'lib/ops_script.rb', line 65 def self.option_parser @option_parser ||= OptionParser.new end |
.options ⇒ Object
57 58 59 |
# File 'lib/ops_script.rb', line 57 def self. @options ||= {} end |
.run ⇒ Object
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 |
# File 'lib/ops_script.rb', line 144 def self.run if already_running? puts "Found #{[:pid_file]} file. Must be running already. Exiting." exit else create_directories create_pid log.level = Logger::INFO unless [:debug] log.info "--" log.info "#{script} starting" end begin if block_given? yield else raise "No block given. Nothing to run." end rescue => e log.error e. log.debug e.backtrace.join('\n') raise ensure log.info "#{script} exiting" log.close remove_pid end end |
.script_basename ⇒ Object
48 49 50 |
# File 'lib/ops_script.rb', line 48 def script_basename File.basename $0, '.*' end |
Instance Method Details
#log ⇒ Object
Use log in your script to log messages
131 132 133 |
# File 'lib/ops_script.rb', line 131 def log OpsScript.log end |
#option_parser ⇒ Object
61 62 63 |
# File 'lib/ops_script.rb', line 61 def option_parser OpsScript.option_parser end |
#options ⇒ Object
53 54 55 |
# File 'lib/ops_script.rb', line 53 def OpsScript. end |