Redirect the “puts” command output to a log file

后端 未结 4 1190
小蘑菇
小蘑菇 2021-01-31 10:49

I am working on creating a daemon in Ruby using the daemons gem. I want to add output from the daemon into a log file. I am wondering what is the easiest way to redirect p

相关标签:
4条回答
  • 2021-01-31 11:14

    I should recommend to use ruby logger, it is better than puts, you can have multiple log levels that you can turn on/off: debug, warn, info,error, etc.

     logger = Logger.new(STDOUT)
     logger = Logger.new("/var/log/my-daemon.log")
    

    I use runit package to manage ruby services, it has svlogd than will redirect daemon output to log file, here is run script for logger process:

    #!/bin/sh
    set -e
    
    LOG=/var/log/my-daemon
    
    test -d "$LOG" || mkdir -p -m2750 "$LOG" && chown nobody:adm "$LOG"
    exec chpst -unobody svlogd -tt "$LOG"
    
    0 讨论(0)
  • Or you can redefine the puts command? Works probably only in a single file/class

    def puts(message)
       #write message to file
    end
    
    0 讨论(0)
  • 2021-01-31 11:29

    If you need to capture both STDERR and STDOUT and don't want to resort to logging, following is a simple solution adapted from this post:

    $stdout.reopen("my.log", "w")
    $stdout.sync = true
    $stderr.reopen($stdout)
    
    0 讨论(0)
  • 2021-01-31 11:40

    Try

    $stdout = File.new( '/tmp/output', 'w' )
    

    To restore:

    $stdout = STDOUT
    
    0 讨论(0)
提交回复
热议问题