Example #1
0
// displayFile opens the specified file and output all lines in it using the
// log object.
func displayFile(log *logger.Logger, fname string) error {
	r, err := os.Open(fname)
	if err != nil {
		return fmt.Errorf("error opening %q: %v", fname, err)
	}
	defer r.Close()

	log.Verbosef(3, "Contents of %q:\n", fname)
	s := bufio.NewScanner(r)
	for s.Scan() {
		log.Verboseln(3, s.Text())
	}
	return nil
}
Example #2
0
// RunCommand executes the given command using the supplied Execute object. The
// method logs the output of the program (stdout/err) using the logger object,
// with a verbosity level of 3. Every output line is prefixed by the current
// HMS. If the Execute object is nil, a new one will be created. outFilter and
// errFilter contain optional slices of substrings which, if matched, will
// cause the entire line to be excluded from the output.
func RunCommand(prefix string, cmd []string, log *logger.Logger, ex Executor, outFilter []string, errFilter []string) error {
	log.Verbosef(2, "%s Start: %s\n", prefix, time.Now().Format(time.Stamp))
	log.Verbosef(1, "%s Command: %q\n", prefix, strings.Join(cmd, " "))

	// Create a new execute object, if current is nil
	e := ex
	if e == nil {
		e = New()
	}

	// Filter functions: These functions will copy stderr and stdout to
	// the log, omitting lines that match our filters.
	errFilterFunc := func(buf string) error {
		if errFilter == nil || !matchSlice(errFilter, buf) {
			log.Verbosef(3, "%s (err): %s\n", hmsNow(), buf)
			return nil
		}
		return nil
	}
	outFilterFunc := func(buf string) error {
		if outFilter == nil || !matchSlice(outFilter, buf) {
			log.Verbosef(3, "%s (out): %s\n", hmsNow(), buf)
			return nil
		}
		return nil
	}

	// All streams copied to output log with "PRE:" as a prefix.
	e.SetStderr(errFilterFunc)
	e.SetStdout(outFilterFunc)

	err := e.Exec(cmd)
	log.Verbosef(2, "%s Finish: %s\n", prefix, time.Now().Format(time.Stamp))
	if err != nil {
		errmsg := fmt.Sprintf("%s returned: %v", prefix, err)
		log.Verbosef(1, "%s\n", errmsg)
		return fmt.Errorf(errmsg)
	}
	log.Verbosef(1, "%s: returned: OK\n", prefix)
	return nil
}