1

I was looking into logging actions for example when you create a new user it sends it to the logger etc.. so every action is logged. I can see how the logger.info sends information into the development.log file.

I was wondering how I Would set-up a different file e.g. users.log and then when I log a line or variable, it saves inside that log file instead of the development.log?

2 Answers2

0

You can specify the file path used in the config file, which can vary according to the environment, as so:

config.paths.log = "/some/path/#{Rails.env}.log"

If you want to create different log files for each model, you can simply create a logger object when needed, as explained in this answer.

However if you just want to somehow mark different logs according to where they were generated, it may be easier to use tagged logging:

logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))
logger.tagged("BCX") { logger.info "Stuff" }                            # Logs "[BCX] Stuff"
logger.tagged("BCX", "Jason") { logger.info "Stuff" }                   # Logs "[BCX] [Jason] Stuff"
logger.tagged("BCX") { logger.tagged("Jason") { logger.info "Stuff" } } # Logs "[BCX] [Jason] Stuff"
Community
  • 1
  • 1
Leo Brito
  • 2,053
  • 13
  • 20
0

Ruby has a Logger class in its standard lib: http://ruby-doc.org/stdlib-2.1.0/libdoc/logger/rdoc/Logger.html

You would instantiate that and pass it the file path of your new log file, like this:

user_log = File.open('logs/users.log', File::WRONLY | File::APPEND)

You can place that in a controller method that your controllers can use. The first string argument is the path to the log file, and the following are opening the file for writing and appending only (so that each log line is added to the log rather than overwriting it each time).

You can customize the format of each log line by setting a formatter:

user_log.formatter = proc { |severity, datetime, progname, msg|
  "#{severity}, #{datetime}, #{progname}, #{msg.dump}"
}
DiegoSalazar
  • 13,361
  • 2
  • 38
  • 55