Sha256: 9cf698b832432b61e3c412c8d57c2e12b9419a6946ccee1f3816984bb47de2de

Contents?: true

Size: 1.79 KB

Versions: 3

Compression:

Stored size: 1.79 KB

Contents

module MultiProcess
  # Can create pipes and multiplex pipe content to put into
  # given IO objects e.g. multiple output from multiple
  # processes to current stdout.
  #
  class Logger < Receiver
    # Create new logger.
    #
    # @param out [IO] IO to push formatted output from
    #   default created logger pipes.
    # @param err [IO] IO to push formatted output from
    #   error sources.
    #
    def initialize(*args)
      @opts  = Hash === args.last ? args.pop : {}
      @out   = args[0] || $stdout
      @err   = args[1] || $stderr

      @colwidth = 0

      super()
    end

    protected

    def received(process, name, line)
      case name
      when :err, :stderr
        output process, line, io: @err, delimiter: 'E>'
      when :out, :stdout
        output process, line
      when :sys
        output(process, line, delimiter: '$>') if @opts[:sys]
      end
    end

    def connected(process, _)
      @colwidth = [process.title.to_s.length, @colwidth].max
    end

    def read(pipe)
      pipe.gets
    end

    def collapse?
      @opts[:collapse].nil? || @opts[:collapse]
    end

    private

    def output(process, line, opts = {})
      opts[:delimiter]   ||= ' |'
      name = if opts[:name]
               opts[:name].to_s.dup
             else
               if process
                 process.title.to_s.rjust(@colwidth, ' ')
               else
                 (' ' * @colwidth)
               end
             end

      io = opts[:io] || @out
      if @last_name == name && collapse?
        io.print " #{' ' * name.length} #{opts[:delimiter]} "
      else
        io.print " #{name} #{opts[:delimiter]} "
      end
      io.puts line
      io.flush

      @last_name = name
    end

    class << self
      def global
        @global ||= new $stdout, $stderr
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
multi_process-1.1.1 lib/multi_process/logger.rb
multi_process-1.1.0 lib/multi_process/logger.rb
multi_process-1.0.0 lib/multi_process/logger.rb