How to format ruby logger?

前端 未结 2 1773
忘掉有多难
忘掉有多难 2021-01-31 08:32

How do you format the ruby logger?

相关标签:
2条回答
  • 2021-01-31 09:14
    logger = Logger.new('nice.log')
    
    logger.formatter = proc do |severity, datetime, progname, msg|
       "NICE: #{msg}\n"
    end
    
    logger.info("I like cheese.")
    
    # nice.log:
    NICE: I like cheese.
    
    0 讨论(0)
  • 2021-01-31 09:32

    If you want to format only the time, you can easily do it with datetime_format and the standard format specification. For example, if you do:

    # Set the logger:
    logger = Logger.new($stdout)
    logger.level = Logger::DEBUG
    logger.datetime_format = "%Y-%m-%d %H:%M:%S"
    
    logger.info("This is an info log...")
    logger.error("This is an error log...")
    

    You will end up with logs such as:

    I, [2015-01-20 14:02:29#17329]  INFO -- myProg: This is an info log...
    E, [2015-01-20 14:02:29#17329] ERROR -- myProg: This is an error log...
    

    If, instead, you want to completely customize your log, you can use logger.formatter. For example, if you do:

    # Set the logger:
    logger = Logger.new($stdout)
    logger.level = Logger::DEBUG
    logger.formatter = proc do |severity, datetime, progname, msg|
        date_format = datetime.strftime("%Y-%m-%d %H:%M:%S")
        if severity == "INFO" or severity == "WARN"
            "[#{date_format}] #{severity}  (#{progname}): #{msg}\n"
        else        
            "[#{date_format}] #{severity} (#{progname}): #{msg}\n"
        end
    end
    
    logger.info("This is an info log...")
    logger.error("This is an error log...")
    

    You will end up with logs such as:

    [2015-01-20 14:48:04] INFO  (myProg): This is an info log...
    [2015-01-20 14:48:04] ERROR (myProg): This is an error log...
    
    0 讨论(0)
提交回复
热议问题