Over a million developers have joined DZone.

Watir Logging

DZone's Guide to

Watir Logging

· ·
Free Resource
// setup logging infrastructure for Watir tests using ruby Logger class

#Logging infrastructure
require 'logger'
# hack ruby logger to format and output only the minimum needed for testing scripts
# Logger is configured to write 
class Logger
  # hack format of logger
  class Formatter
    #original: Format = "%s, [%s#%d] %5s -- %s: %s\n"
    #Change the name of constant to avoid redefining the super which bugs us a bit. So let it be Formato then.
    Formato = "[%s] [%5s] : %s\n" 
    #keep the original signature but alter implementation to change formatting
    def call(severity, time, progname, msg)
      #add logging to stdout
      puts output_message = msg2str(msg)
      #original: Format % [severity[0..0], format_datetime(time), $$, severity, progname, msg2str(msg)]
      Formato % [format_datetime(time),severity, output_message]

logfile = File.join(File.dirname(__FILE__),'..','log', 'logger.log')
$log = Logger.new(logfile,'daily')
$log.level = Logger::DEBUG
$log.datetime_format = "%H:%M:%S"
$log.info("Watir Execution Starts")
$log.debug("Halllow Worled!")
$log.info("Achtung Achtung. The Train will leave from platform 9")
$log.warn("no no no no no. you can't do this")
$log.error("error error Danger Danger")
$log.fatal("game over game over game over")
# example of output
#[13:02:00] [DEBUG] : Watir Execution Starts
#[13:02:00] [DEBUG] : Halllow Worled!
#[13:02:00] [ INFO] : Achtung Achtung. The Train will leave from platform 9
#[13:02:00] [ WARN] : no no no no no. you can't do this
#[13:02:00] [ERROR] : error error Danger Danger
#[13:02:00] [FATAL] : game over game over game over

# alternative is to wrap a method around this thing and avoid the global $log which would be cleaner

def log
  @log |= Logger.new(logfile, 'daily')
  # make the method in scope 'main'. it can live in a Module but do include the Module in main


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}