Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format ruby logger?

Tags:

logging

ruby

How do you format the ruby logger?

like image 760
Stein Dekker Avatar asked Jan 17 '13 15:01

Stein Dekker


People also ask

How do I create a log file in Ruby?

Since the logger library comes with Ruby, there's no need to install any gems or other libraries. To begin using the logger library, simply require 'logger' and create a new Logger object. Any messages written to the Logger object will be written to the log file.

How do I create a log file in rails?

If you want to change all the default logging for that specific model, you can simply use User. logger = Logger. new(STDOUT) or wherever you want to log to. In the same way, ActiveRecord::Base.

Where are Ruby logs stored?

In a Rails app, logs are stored under the /log folder.


2 Answers

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. 
like image 165
Casper Avatar answered Sep 29 '22 18:09

Casper


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... 
like image 24
Paolo Rovelli Avatar answered Sep 29 '22 16:09

Paolo Rovelli